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 '*.sln' -o -name '*.csproj' -o -name 'nuget.config' \) \
          ! -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
    environment:
      ADAS_NUGET_URL:
        from_secret: ADAS_NUGET_URL
    commands:
      - set -eu
      - mkdir -p ci-evidence/test-results/dotnet
      - dotnet --info > ci-evidence/dotnet-info.txt
      - (dotnet nuget add source "${ADAS_NUGET_URL}" -n "ADAS Nugget Server") 2>/dev/null || true
      - dotnet restore "adas-core/adas-core.csproj"
      - dotnet restore "./adas-core.Test/adas-core.Test.csproj"
      - set +e
      - dotnet build --configuration Debug /p:Platform=x64 /nowarn:1701,1702,IL2121,CS1591,CS1587,CA1416 "adas-core/adas-core.csproj"
      - BUILD_EXIT=$?
      - dotnet test --configuration Debug /p:Platform=x64 /nowarn:1701,1702,IL2121,CS1591,CS1587,CA1416 "./adas-core.Test/adas-core.Test.csproj" --results-directory ci-evidence/test-results/dotnet --logger "trx;LogFileName=adas-core-tests.trx"
      - TEST_EXIT=$?
      - set -e
      - |
        cat > ci-evidence/test-results/dotnet-summary.json <<EOF
        {
          "status": "executed",
          "build_exit_code": ${BUILD_EXIT},
          "test_exit_code": ${TEST_EXIT},
          "build_target": "adas-core/adas-core.csproj",
          "test_target": "./adas-core.Test/adas-core.Test.csproj"
        }
        EOF
      - test "$BUILD_EXIT" -eq 0
      - 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:
      CI_REGISTRY_USER:
        from_secret: CI_REGISTRY_USER
      CI_REGISTRY_PASSWORD:
        from_secret: CI_REGISTRY_PASSWORD
      CI_REGISTRY:
        from_secret: CI_REGISTRY
    commands:
      - set -eu
      - mkdir -p ci-evidence
      - docker login "${CI_REGISTRY}" -u "${CI_REGISTRY_USER}" -p "${CI_REGISTRY_PASSWORD}"
      - 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="${CI_REGISTRY}/adas/adas-core/adas-core"
      - 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:
      CI_REGISTRY_USER:
        from_secret: CI_REGISTRY_USER
      CI_REGISTRY_PASSWORD:
        from_secret: CI_REGISTRY_PASSWORD
      CI_REGISTRY:
        from_secret: CI_REGISTRY
    commands:
      - set -eu
      - mkdir -p /root/.docker ci-evidence
      - |
        cat > /root/.docker/config.json <<EOF
        {
          "auths": {
            "${CI_REGISTRY}": {
              "username": "${CI_REGISTRY_USER}",
              "password": "${CI_REGISTRY_PASSWORD}"
            }
          }
        }
        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)"
      - |
        jq -n \
          --arg project "ADAS" \
          --arg component "adas-core" \
          --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 backend_tests "$DOTNET_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: $backend_tests
            }
          }' > ci-evidence/build-metadata.json
      - sha256sum ci-evidence/* > ci-evidence/checksums-predeploy.txt || true

  deploy_adas_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-core-dev && \
           docker compose stop adas-core && \
           docker compose rm -f adas-core && \
           docker compose pull adas-core && \
           docker compose up -d adas-core"
      - |
        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_adas_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-core-pre && \
           docker compose stop adas-core && \
           docker compose rm -f adas-core && \
           docker compose pull adas-core && \
           docker compose up -d adas-core"
      - |
        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/core/${ENV_NAME}"
      - scp -o "StrictHostKeyChecking yes" "ci-evidence-${RELEASE_ID}.tar.gz" "${DEPLOY_USER}@${EVIDENCE_HOST}:/opt/adas-ci-evidence/core/${ENV_NAME}/"
