# ===============================================================================================================
# bitbucket-pipelines.yml - Pipeline CI/CD para proyectosacc
# Descripción:
#       Pipeline de 7 pasos estándar de CCsoft para desplegar infraestructura (Terraform),
#       frontend React (S3+CloudFront) y API backend (EC2) de SACC.
#
# Autor: Área de Tecnología y Desarrollo - CCsoft
# ===============================================================================================================

image: atlassian/default-image:5

options:
  oidc:
    audiences:
      - sts.amazonaws.com

  definitions:
    steps:
      - step: &notify-start
          name: Notify Start
          script:
            - export TELEGRAM_BOT_TOKEN="${TELEGRAM_BOT_TOKEN}"
            - export TELEGRAM_CHAT_ID="${TELEGRAM_CHAT_ID}"
            - bash scripts/telegram-pipeline-notify.sh start

      - step: &notify-fail
          name: Notify Failure
          script:
            - export TELEGRAM_BOT_TOKEN="${TELEGRAM_BOT_TOKEN}"
            - export TELEGRAM_CHAT_ID="${TELEGRAM_CHAT_ID}"
            - bash scripts/telegram-pipeline-notify.sh failure "Paso: ${BITBUCKET_STEP_KEY}"

pipelines:
  default:
    - step:
        name: 04_build
        script:
          - set -euo pipefail
          - echo "=== Build de proyectosacc (sin deploy) ==="
          - npm ci
          - npm run build
          - ./gradlew clean bootJar

  branches:
    developer:
      - step:
          name: 01_image-setup
          script:
            - set -euo pipefail
            - apt-get update -y && apt-get install -y openssh-client openjdk-21-jdk wget unzip curl
            - curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
            - unzip -q awscliv2.zip
            - ./aws/install
            - aws --version
            - mkdir -p ~/.ssh
            - echo "${DEV_SSH_PRIVATE_KEY_THOTH_PROYECTOSACC}" | base64 -d > ~/.ssh/sacc4_key
            - chmod 600 ~/.ssh/sacc4_key
            - ssh-keyscan -p "${DEV_SSH_PORT_PROYECTOSACC:-22}" "${DEV_SERVER_IP_PROYECTOSACC}" >> ~/.ssh/known_hosts 2>/dev/null || true
            - export TELEGRAM_BOT_TOKEN="${DEV_TELEGRAM_BOT_TOKEN}"
            - export TELEGRAM_CHAT_ID="${DEV_TELEGRAM_CHAT_ID}"
            - bash scripts/telegram-pipeline-notify.sh start

      - step:
          name: 03_terraform
          oidc: true
          script:
            - set -euo pipefail
            - source scripts/aws-oidc-setup.sh dev
            - cd terraform
            - wget -q "https://releases.hashicorp.com/terraform/1.11.4/terraform_1.11.4_linux_amd64.zip"
            - unzip -q terraform_1.11.4_linux_amd64.zip
            - mv terraform /usr/local/bin/terraform
            - terraform version
            - export AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-mx-central-1}"
            - terraform init -backend-config=backend.dev.hcl
            - terraform plan -var-file=environments/dev.tfvars -var="db_password=${DEV_DB_PASSWORD}" -out=dev.tfplan
            - terraform apply -auto-approve dev.tfplan
            - terraform output -json > terraform-outputs.json
            - cat terraform-outputs.json
          artifacts:
            - terraform/terraform-outputs.json

      - step:
          name: 04_build
          script:
            - set -euo pipefail
            - npm ci
            - npm run build
            - ./gradlew clean bootJar
          artifacts:
            - build/**
            - build/libs/*.jar

      - step:
          name: 05_publish
          oidc: true
          script:
            - set -euo pipefail
            - source scripts/aws-oidc-setup.sh dev
            - aws s3 sync build/ "s3://${DEV_S3_FRONTEND_BUCKET}/" --delete
            - aws s3 cp build/libs/*.jar "s3://${DEV_S3_ARTIFACTS_BUCKET}/develop/proyectosacc-app.jar"

      - step:
          name: 06_install
          script:
            - set -euo pipefail
            - echo "${DEV_SSH_PRIVATE_KEY_THOTH_PROYECTOSACC}" | base64 -d > ~/.ssh/sacc4_key
            - chmod 600 ~/.ssh/sacc4_key
            - |
              ssh -p "${DEV_SSH_PORT_PROYECTOSACC:-22}" \
                -i ~/.ssh/sacc4_key \
                -o StrictHostKeyChecking=no \
                "${DEV_SERVER_USER_PROYECTOSACC:-thoth}@${DEV_SERVER_IP_PROYECTOSACC}" \
                "bash -c 'mkdir -p /home/thoth/deploy/artifacts/current && aws s3 cp s3://${DEV_S3_ARTIFACTS_BUCKET}/develop/proyectosacc-app.jar /home/thoth/deploy/artifacts/current/proyectosacc-app.jar && chown osiris:osiris /home/thoth/deploy/artifacts/current/proyectosacc-app.jar'"

      - step:
          name: 07_deploy
          oidc: true
          script:
            - set -euo pipefail
            - source scripts/aws-oidc-setup.sh dev
            - echo "${DEV_SSH_PRIVATE_KEY_THOTH_PROYECTOSACC}" | base64 -d > ~/.ssh/sacc4_key
            - chmod 600 ~/.ssh/sacc4_key
            - |
              ssh -p "${DEV_SSH_PORT_PROYECTOSACC:-22}" \
                -i ~/.ssh/sacc4_key \
                -o StrictHostKeyChecking=no \
                "${DEV_SERVER_USER_PROYECTOSACC:-thoth}@${DEV_SERVER_IP_PROYECTOSACC}" \
                "bash /home/thoth/deploy/setup/deploy.sh"
            - export CLOUDFRONT_DISTRIBUTION_ID=$(python3 -c "import json; print(json.load(open('terraform/terraform-outputs.json'))['cloudfront_distribution_id']['value'])")
            - aws cloudfront create-invalidation --distribution-id "${CLOUDFRONT_DISTRIBUTION_ID}" --paths "/*"
            - export TELEGRAM_BOT_TOKEN="${DEV_TELEGRAM_BOT_TOKEN}"
            - export TELEGRAM_CHAT_ID="${DEV_TELEGRAM_CHAT_ID}"
            - bash scripts/telegram-pipeline-notify.sh success "CloudFront invalidado"

    master:
      - step:
          name: 01_image-setup
          script:
            - set -euo pipefail
            - apt-get update -y && apt-get install -y openssh-client openjdk-21-jdk wget unzip curl
            - curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
            - unzip -q awscliv2.zip
            - ./aws/install
            - aws --version
            - mkdir -p ~/.ssh
            - echo "${PROD_SSH_PRIVATE_KEY_THOTH_PROYECTOSACC}" | base64 -d > ~/.ssh/sacc4_key
            - chmod 600 ~/.ssh/sacc4_key
            - ssh-keyscan -p "${PROD_SSH_PORT_PROYECTOSACC:-22}" "${PROD_SERVER_IP_PROYECTOSACC}" >> ~/.ssh/known_hosts 2>/dev/null || true
            - export TELEGRAM_BOT_TOKEN="${PROD_TELEGRAM_BOT_TOKEN}"
            - export TELEGRAM_CHAT_ID="${PROD_TELEGRAM_CHAT_ID}"
            - bash scripts/telegram-pipeline-notify.sh start

      - step:
          name: 03_terraform
          oidc: true
          script:
            - set -euo pipefail
            - source scripts/aws-oidc-setup.sh prod
            - cd terraform
            - wget -q "https://releases.hashicorp.com/terraform/1.11.4/terraform_1.11.4_linux_amd64.zip"
            - unzip -q terraform_1.11.4_linux_amd64.zip
            - mv terraform /usr/local/bin/terraform
            - terraform version
            - export AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-mx-central-1}"
            - terraform init -backend-config=backend.prod.hcl
            - terraform plan -var-file=environments/prod.tfvars -var="db_password=${PROD_DB_PASSWORD}" -out=prod.tfplan
            - terraform apply -auto-approve prod.tfplan
            - terraform output -json > terraform-outputs.json
            - cat terraform-outputs.json
          artifacts:
            - terraform/terraform-outputs.json

      - step:
          name: 04_build
          script:
            - set -euo pipefail
            - npm ci
            - npm run build
            - ./gradlew clean bootJar
          artifacts:
            - build/**
            - build/libs/*.jar

      - step:
          name: 05_publish
          oidc: true
          script:
            - set -euo pipefail
            - source scripts/aws-oidc-setup.sh prod
            - aws s3 sync build/ "s3://${PROD_S3_FRONTEND_BUCKET}/" --delete
            - aws s3 cp build/libs/*.jar "s3://${PROD_S3_ARTIFACTS_BUCKET}/main/proyectosacc-app.jar"

      - step:
          name: 06_install
          script:
            - set -euo pipefail
            - echo "${PROD_SSH_PRIVATE_KEY_THOTH_PROYECTOSACC}" | base64 -d > ~/.ssh/sacc4_key
            - chmod 600 ~/.ssh/sacc4_key
            - |
              ssh -p "${PROD_SSH_PORT_PROYECTOSACC:-22}" \
                -i ~/.ssh/sacc4_key \
                -o StrictHostKeyChecking=no \
                "${PROD_SERVER_USER_PROYECTOSACC:-thoth}@${PROD_SERVER_IP_PROYECTOSACC}" \
                "bash -c 'mkdir -p /home/thoth/deploy/artifacts/current && aws s3 cp s3://${PROD_S3_ARTIFACTS_BUCKET}/main/proyectosacc-app.jar /home/thoth/deploy/artifacts/current/proyectosacc-app.jar && chown osiris:osiris /home/thoth/deploy/artifacts/current/proyectosacc-app.jar'"

      - step:
          name: 06b_notify_approval
          script:
            - set -euo pipefail
            - export TELEGRAM_BOT_TOKEN="${PROD_TELEGRAM_BOT_TOKEN}"
            - export TELEGRAM_CHAT_ID="${PROD_TELEGRAM_CHAT_ID}"
            - |
              bash scripts/telegram-pipeline-notify.sh start "⏸️ Pipeline pausado esperando aprobación manual para deploy a PRODUCCIÓN. Ve a Bitbucket > Pipelines > proyectosacc > master para aprobar o rechazar."

      - step:
          name: 07_deploy
          oidc: true
          deployment: production
          trigger: manual
          script:
            - set -euo pipefail
            - source scripts/aws-oidc-setup.sh prod
            - echo "${PROD_SSH_PRIVATE_KEY_THOTH_PROYECTOSACC}" | base64 -d > ~/.ssh/sacc4_key
            - chmod 600 ~/.ssh/sacc4_key
            - |
              ssh -p "${PROD_SSH_PORT_PROYECTOSACC:-22}" \
                -i ~/.ssh/sacc4_key \
                -o StrictHostKeyChecking=no \
                "${PROD_SERVER_USER_PROYECTOSACC:-thoth}@${PROD_SERVER_IP_PROYECTOSACC}" \
                "bash /home/thoth/deploy/setup/deploy.sh"
            - export CLOUDFRONT_DISTRIBUTION_ID=$(python3 -c "import json; print(json.load(open('terraform/terraform-outputs.json'))['cloudfront_distribution_id']['value'])")
            - aws cloudfront create-invalidation --distribution-id "${CLOUDFRONT_DISTRIBUTION_ID}" --paths "/*"
            - export TELEGRAM_BOT_TOKEN="${PROD_TELEGRAM_BOT_TOKEN}"
            - export TELEGRAM_CHAT_ID="${PROD_TELEGRAM_CHAT_ID}"
            - bash scripts/telegram-pipeline-notify.sh success "CloudFront invalidado | Deploy a PROD aprobado y completado"
