steps:
  collect_inputs:
    image: alpine:3.20
    # Se ejecuta en todas las ramas: features, env/adas/dev, env/adas/pre
    commands:
      - set -eu
      - apk add --no-cache jq coreutils git findutils
      - mkdir -p ci-evidence/test-results
      - SHORT_SHA="$(printf "%s" "${DRONE_COMMIT_SHA}" | cut -c1-12)"
      - BUILD_TIME="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
      - ENV_NAME="$(printf "%s" "${DRONE_BRANCH}" | sed 's|env/adas/||')"
      - RELEASE_ID="${RELEASE_ID:-REL-${ENV_NAME}-${DRONE_BUILD_NUMBER}-${SHORT_SHA}}"
      - echo "$BUILD_TIME" > ci-evidence/build-time.txt
      - echo "${DRONE_COMMIT_SHA}" > ci-evidence/commit-sha.txt
      - echo "${SHORT_SHA}" > ci-evidence/commit-short.txt
      - echo "${DRONE_BRANCH}" > ci-evidence/branch.txt
      - echo "${ENV_NAME}" > ci-evidence/env-name.txt
      - echo "${DRONE_BUILD_NUMBER}" > ci-evidence/pipeline-id.txt
      - echo "${RELEASE_ID}" > ci-evidence/release-id.txt
      - echo "Teralevel CI" > ci-evidence/ci-tool.txt
      - git rev-parse --short HEAD > ci-evidence/git-short-head.txt
      - git rev-parse HEAD > ci-evidence/git-full-head.txt
      - git status --short > ci-evidence/git-status.txt || true
      - |
        find . \
          -maxdepth 4 \
          -type f \
          \( -name 'Dockerfile' -o -name '.teralevel-ci.yml' -o -name 'package-lock.json' -o -name 'angular.json' -o -name '*.sln' -o -name '*.csproj' -o -name 'nuget.config' \) \
          ! -path '*/node_modules/*' \
          ! -path '*/bin/*' \
          ! -path '*/obj/*' \
          -exec sha256sum {} \; > ci-evidence/input-checksums.txt || true
      - |
        jq -n \
          --arg release_id "$RELEASE_ID" \
          --arg ur_prd_version "${UR_PRD_VERSION:-PENDIENTE}" \
          --arg srs_version "${SRS_VERSION:-PENDIENTE}" \
          --arg rmf_version "${RMF_VERSION:-PENDIENTE}" \
          --arg trace_version "${TRACE_MATRIX_VERSION:-PENDIENTE}" \
          --arg sbom_ref "ci-evidence/sbom-cyclonedx.json" \
          '{
            release_id: $release_id,
            ur_prd_version: $ur_prd_version,
            srs_version: $srs_version,
            rmf_version: $rmf_version,
            traceability_matrix_version: $trace_version,
            sbom_reference: $sbom_ref
          }' > ci-evidence/release-baseline-ref.json

  test_backend:
    image: mcr.microsoft.com/dotnet/sdk:8.0
    # Se ejecuta en todas las ramas: features, env/adas/dev, env/adas/pre
    commands:
      - set -eu
      - mkdir -p ci-evidence/test-results/dotnet
      - dotnet --info > ci-evidence/dotnet-info.txt
      - SOLUTION="$(find . -maxdepth 4 -type f -name '*.sln' ! -path '*/obj/*' ! -path '*/bin/*' | head -n 1 || true)"
      - |
        if [ -z "$SOLUTION" ]; then
          TEST_PROJECTS="$(find . -maxdepth 5 -type f \( -name '*Test*.csproj' -o -name '*Tests*.csproj' \) ! -path '*/obj/*' ! -path '*/bin/*' | tr '\n' ' ' || true)"
        else
          TEST_PROJECTS=""
        fi
      - |
        if [ -n "$SOLUTION" ]; then
          dotnet restore "$SOLUTION"
          set +e
          dotnet test "$SOLUTION" \
            --configuration Release \
            --results-directory ci-evidence/test-results/dotnet \
            --logger "trx;LogFileName=dotnet-tests.trx"
          TEST_EXIT=$?
          set -e
        elif [ -n "$TEST_PROJECTS" ]; then
          TEST_EXIT=0
          for proj in $TEST_PROJECTS; do
            dotnet restore "$proj"
            set +e
            dotnet test "$proj" \
              --configuration Release \
              --results-directory ci-evidence/test-results/dotnet \
              --logger "trx;LogFileName=$(basename "$proj" .csproj)-tests.trx"
            CUR_EXIT=$?
            set -e
            if [ "$CUR_EXIT" -ne 0 ]; then TEST_EXIT=$CUR_EXIT; fi
          done
        else
          TEST_EXIT=0
        fi
      - |
        if [ -n "$SOLUTION" ] || [ -n "${TEST_PROJECTS:-}" ]; then
          STATUS="executed"
        else
          STATUS="skipped"
        fi
      - |
        cat > ci-evidence/test-results/dotnet-summary.json <<EOF
        {
          "status": "${STATUS}",
          "exit_code": ${TEST_EXIT},
          "target": "$(if [ -n "$SOLUTION" ]; then printf "%s" "$SOLUTION"; else printf "%s" "${TEST_PROJECTS:-none}"; fi)"
        }
        EOF
      - test "$TEST_EXIT" -eq 0

  test_frontend:
    # NOTA: Chromium se instala en cada ejecucion (~1-3 min adicionales).
    # Cuando este disponible, sustituir por una imagen base propia:
    #   git.teralevel.io/adas/node-chrome:20  (node:20-bookworm-slim + chromium pre-instalado)
    # Eso eliminara el apt-get de este paso y reducira el tiempo total del pipeline.
    image: node:20-bookworm-slim
    # Se ejecuta en todas las ramas: features, env/adas/dev, env/adas/pre
    commands:
      - set -eu
      - apt-get update
      - apt-get install -y --no-install-recommends chromium jq ca-certificates
      - rm -rf /var/lib/apt/lists/*
      - mkdir -p ci-evidence/test-results/frontend
      - node --version > ci-evidence/node-version.txt
      - npm --version > ci-evidence/npm-version.txt
      - FRONTEND_DIR="$(find . -maxdepth 4 -type f -name 'angular.json' ! -path '*/node_modules/*' -exec dirname {} \; | head -n 1 || true)"
      - |
        if [ -z "$FRONTEND_DIR" ]; then
          FRONTEND_DIR="$(find . -maxdepth 4 -type f -name 'package.json' ! -path '*/node_modules/*' -exec dirname {} \; | head -n 1 || true)"
        fi
      - |
        if [ -n "$FRONTEND_DIR" ]; then
          cd "$FRONTEND_DIR"
          export CI=true
          export CHROME_BIN=/usr/bin/chromium
          npm ci
          set +e
          npm test -- --watch=false --browsers=ChromeHeadless --progress=false
          TEST_EXIT=$?
          set -e
          cd -
          STATUS="executed"
        else
          TEST_EXIT=0
          STATUS="skipped"
        fi
      - |
        cat > ci-evidence/test-results/frontend-summary.json <<EOF
        {
          "status": "${STATUS}",
          "exit_code": ${TEST_EXIT},
          "target": "${FRONTEND_DIR:-none}"
        }
        EOF
      - test "$TEST_EXIT" -eq 0

  build_and_push:
    # Requiere que el runner CI tenga /var/run/docker.sock montado (daemon Docker en CI)
    image: docker:27-cli
    when:
      branch:
        - env/adas/dev
        - env/adas/pre
    environment:
      REGISTRY_USER:
        from_secret: REGISTRY_USER
      REGISTRY_PASS:
        from_secret: REGISTRY_PASS
    commands:
      - set -eu
      - mkdir -p ci-evidence
      - docker login "git.teralevel.io" -u "${REGISTRY_USER}" -p "${REGISTRY_PASS}"
      - SHORT_SHA="$(cat ci-evidence/commit-short.txt)"
      - PIPELINE_ID="$(cat ci-evidence/pipeline-id.txt)"
      - ENV_NAME="$(cat ci-evidence/env-name.txt)"
      - IMAGE_REPO="git.teralevel.io/adas/adas-webdisplay"
      - IMAGE_TAG_IMMUTABLE="${ENV_NAME}-${PIPELINE_ID}-${SHORT_SHA}"
      - IMAGE_REF_IMMUTABLE="${IMAGE_REPO}:${IMAGE_TAG_IMMUTABLE}"
      - IMAGE_REF_MUTABLE="${IMAGE_REPO}:${ENV_NAME}-latest"
      - echo "$IMAGE_REF_IMMUTABLE" > ci-evidence/image-ref-immutable.txt
      - echo "$IMAGE_REF_MUTABLE" > ci-evidence/image-ref-mutable.txt
      - docker version > ci-evidence/docker-version.txt
      - |
        docker build \
          --label org.opencontainers.image.revision="${DRONE_COMMIT_SHA}" \
          --label org.opencontainers.image.version="${IMAGE_TAG_IMMUTABLE}" \
          --label org.opencontainers.image.created="$(cat ci-evidence/build-time.txt)" \
          -t "${IMAGE_REF_IMMUTABLE}" \
          -t "${IMAGE_REF_MUTABLE}" \
          -f Dockerfile \
          . > ci-evidence/docker-build.log 2>&1 || { cat ci-evidence/docker-build.log; exit 1; }
      - docker push "${IMAGE_REF_IMMUTABLE}" 2>&1 | tee -a ci-evidence/docker-build.log
      - docker push "${IMAGE_REF_MUTABLE}" 2>&1 | tee -a ci-evidence/docker-build.log
      - |
        docker image inspect "${IMAGE_REF_IMMUTABLE}" \
          --format '{{index .RepoDigests 0}}' > ci-evidence/image-digest.txt 2>/dev/null \
        || docker image inspect "${IMAGE_REF_IMMUTABLE}" \
          --format '{{.Id}}' > ci-evidence/image-digest.txt
      - cat ci-evidence/docker-build.log

  generate_sbom:
    image: anchore/syft:v1.18.1
    when:
      branch:
        - env/adas/dev
        - env/adas/pre
    environment:
      REGISTRY_USER:
        from_secret: REGISTRY_USER
      REGISTRY_PASS:
        from_secret: REGISTRY_PASS
    commands:
      - set -eu
      - mkdir -p /root/.docker ci-evidence
      - |
        cat > /root/.docker/config.json <<EOF
        {
          "auths": {
            "git.teralevel.io": {
              "username": "$REGISTRY_USER",
              "password": "$REGISTRY_PASS"
            }
          }
        }
        EOF
      - IMAGE_REF_IMMUTABLE="$(cat ci-evidence/image-ref-immutable.txt)"
      - syft version > ci-evidence/syft-version.txt
      - syft "${IMAGE_REF_IMMUTABLE}" -o cyclonedx-json=ci-evidence/sbom-cyclonedx.json
      - syft "${IMAGE_REF_IMMUTABLE}" -o spdx-json=ci-evidence/sbom-spdx.json

  assemble_ci_evidence_predeploy:
    image: alpine:3.20
    when:
      branch:
        - env/adas/dev
        - env/adas/pre
    commands:
      - set -eu
      - apk add --no-cache jq coreutils
      - BUILD_TIME="$(cat ci-evidence/build-time.txt)"
      - COMMIT_SHA="$(cat ci-evidence/commit-sha.txt)"
      - SHORT_SHA="$(cat ci-evidence/commit-short.txt)"
      - BRANCH="$(cat ci-evidence/branch.txt)"
      - ENV_NAME="$(cat ci-evidence/env-name.txt)"
      - PIPELINE_ID="$(cat ci-evidence/pipeline-id.txt)"
      - RELEASE_ID="$(cat ci-evidence/release-id.txt)"
      - IMAGE_REF_IMMUTABLE="$(cat ci-evidence/image-ref-immutable.txt)"
      - IMAGE_REF_MUTABLE="$(cat ci-evidence/image-ref-mutable.txt)"
      - IMAGE_DIGEST="$(cat ci-evidence/image-digest.txt)"
      - DOTNET_SUMMARY="$(cat ci-evidence/test-results/dotnet-summary.json)"
      - FRONTEND_SUMMARY="$(cat ci-evidence/test-results/frontend-summary.json)"
      - |
        jq -n \
          --arg project "ADAS" \
          --arg component "adas-webdisplay" \
          --arg environment "$ENV_NAME" \
          --arg release_id "$RELEASE_ID" \
          --arg build_time_utc "$BUILD_TIME" \
          --arg commit_sha "$COMMIT_SHA" \
          --arg commit_short "$SHORT_SHA" \
          --arg branch "$BRANCH" \
          --arg pipeline_id "$PIPELINE_ID" \
          --arg ci_tool "Teralevel CI" \
          --arg image_ref_immutable "$IMAGE_REF_IMMUTABLE" \
          --arg image_ref_mutable "$IMAGE_REF_MUTABLE" \
          --arg image_digest "$IMAGE_DIGEST" \
          --argjson dotnet_tests "$DOTNET_SUMMARY" \
          --argjson frontend_tests "$FRONTEND_SUMMARY" \
          '{
            project: $project,
            component: $component,
            environment: $environment,
            release_id: $release_id,
            build_time_utc: $build_time_utc,
            commit_sha: $commit_sha,
            commit_short: $commit_short,
            branch: $branch,
            pipeline_id: $pipeline_id,
            ci_tool: $ci_tool,
            image_ref_immutable: $image_ref_immutable,
            image_ref_mutable: $image_ref_mutable,
            image_digest: $image_digest,
            tests: {
              backend: $dotnet_tests,
              frontend: $frontend_tests
            }
          }' > ci-evidence/build-metadata.json
      - sha256sum ci-evidence/* > ci-evidence/checksums-predeploy.txt || true

  deploy_webdisplay_dev:
    image: alpine:3.20
    when:
      branch:
        - env/adas/dev
    environment:
      ADAS_SSH_KEY:
        from_secret: ADAS_SSH_KEY
      SSH_SERVER_HOSTKEYS:
        from_secret: SSH_SERVER_HOSTKEYS
      DEPLOY_HOST_DEV:
        from_secret: DEPLOY_HOST_DEV
      DEPLOY_USER:
        from_secret: DEPLOY_USER
    commands:
      - set -eu
      - apk add --no-cache openssh-client jq
      - mkdir -p ~/.ssh
      - echo "$ADAS_SSH_KEY" > ~/.ssh/id_ed25519
      - chmod 600 ~/.ssh/id_ed25519
      - echo "$SSH_SERVER_HOSTKEYS" >> ~/.ssh/known_hosts
      - chmod 644 ~/.ssh/known_hosts
      - IMAGE_REF_MUTABLE="$(cat ci-evidence/image-ref-mutable.txt)"
      - |
        ssh -o "StrictHostKeyChecking yes" "${DEPLOY_USER}@${DEPLOY_HOST_DEV}" \
          "cd /opt/adas-icu-dev && \
           docker compose stop webdisplay-dev && \
           docker compose rm -f webdisplay-dev && \
           docker compose pull webdisplay-dev && \
           docker compose up -d webdisplay-dev"
      - |
        REMOTE_DIGEST="$(ssh -o "StrictHostKeyChecking yes" "${DEPLOY_USER}@${DEPLOY_HOST_DEV}" \
          "docker image inspect ${IMAGE_REF_MUTABLE} --format='{{index .RepoDigests 0}}'")"
      - |
        jq -n \
          --arg environment "dev" \
          --arg host "${DEPLOY_HOST_DEV}" \
          --arg deployed_ref "$IMAGE_REF_MUTABLE" \
          --arg deployed_digest "$REMOTE_DIGEST" \
          '{
            environment: $environment,
            host: $host,
            deployed_ref: $deployed_ref,
            deployed_digest: $deployed_digest
          }' > ci-evidence/deploy-info.json

  deploy_webdisplay_pre:
    image: alpine:3.20
    when:
      branch:
        - env/adas/pre
    environment:
      ADAS_SSH_KEY:
        from_secret: ADAS_SSH_KEY
      SSH_SERVER_HOSTKEYS:
        from_secret: SSH_SERVER_HOSTKEYS
      DEPLOY_HOST_PRE:
        from_secret: DEPLOY_HOST_PRE
      DEPLOY_USER:
        from_secret: DEPLOY_USER
    commands:
      - set -eu
      - apk add --no-cache openssh-client jq
      - mkdir -p ~/.ssh
      - echo "$ADAS_SSH_KEY" > ~/.ssh/id_ed25519
      - chmod 600 ~/.ssh/id_ed25519
      - echo "$SSH_SERVER_HOSTKEYS" >> ~/.ssh/known_hosts
      - chmod 644 ~/.ssh/known_hosts
      - IMAGE_REF_MUTABLE="$(cat ci-evidence/image-ref-mutable.txt)"
      - |
        ssh -o "StrictHostKeyChecking yes" "${DEPLOY_USER}@${DEPLOY_HOST_PRE}" \
          "cd /opt/adas-icu-pre && \
           docker compose stop webdisplay-pre && \
           docker compose rm -f webdisplay-pre && \
           docker compose pull webdisplay-pre && \
           docker compose up -d webdisplay-pre"
      - |
        REMOTE_DIGEST="$(ssh -o "StrictHostKeyChecking yes" "${DEPLOY_USER}@${DEPLOY_HOST_PRE}" \
          "docker image inspect ${IMAGE_REF_MUTABLE} --format='{{index .RepoDigests 0}}'")"
      - |
        jq -n \
          --arg environment "pre" \
          --arg host "${DEPLOY_HOST_PRE}" \
          --arg deployed_ref "$IMAGE_REF_MUTABLE" \
          --arg deployed_digest "$REMOTE_DIGEST" \
          '{
            environment: $environment,
            host: $host,
            deployed_ref: $deployed_ref,
            deployed_digest: $deployed_digest
          }' > ci-evidence/deploy-info.json

  finalize_and_publish_ci_evidence:
    image: alpine:3.20
    when:
      branch:
        - env/adas/dev
        - env/adas/pre
    environment:
      ADAS_SSH_KEY:
        from_secret: ADAS_SSH_KEY
      SSH_SERVER_HOSTKEYS:
        from_secret: SSH_SERVER_HOSTKEYS
      DEPLOY_HOST_DEV:
        from_secret: DEPLOY_HOST_DEV
      DEPLOY_HOST_PRE:
        from_secret: DEPLOY_HOST_PRE
      DEPLOY_USER:
        from_secret: DEPLOY_USER
    commands:
      - set -eu
      - apk add --no-cache openssh-client jq coreutils tar gzip
      - mkdir -p ~/.ssh
      - echo "$ADAS_SSH_KEY" > ~/.ssh/id_ed25519
      - chmod 600 ~/.ssh/id_ed25519
      - echo "$SSH_SERVER_HOSTKEYS" >> ~/.ssh/known_hosts
      - chmod 644 ~/.ssh/known_hosts
      - RELEASE_ID="$(cat ci-evidence/release-id.txt)"
      - ENV_NAME="$(cat ci-evidence/env-name.txt)"
      - sha256sum ci-evidence/* > ci-evidence/checksums-final.txt || true
      - tar -czf "ci-evidence-${RELEASE_ID}.tar.gz" ci-evidence
      - |
        if [ "${ENV_NAME}" = "dev" ]; then
          EVIDENCE_HOST="${DEPLOY_HOST_DEV}"
        else
          EVIDENCE_HOST="${DEPLOY_HOST_PRE}"
        fi
      - ssh -o "StrictHostKeyChecking yes" "${DEPLOY_USER}@${EVIDENCE_HOST}" "mkdir -p /opt/adas-ci-evidence/webdisplay/${ENV_NAME}"
      - scp -o "StrictHostKeyChecking yes" "ci-evidence-${RELEASE_ID}.tar.gz" "${DEPLOY_USER}@${EVIDENCE_HOST}:/opt/adas-ci-evidence/webdisplay/${ENV_NAME}/"
