image: docker:20.10.16
options:
  size: 2x
pipelines:
  custom:
    deploy-staging:
      - step:
          name: Build and Push to Staging
          services:
            - docker
          script:
            - |
              IMAGE_NAME=harbor.external.prod.ascendro.io/saas-staging/mietwerte:latest
              printf '%s\n' "$HARBOR_PASSWORD" | docker login -u "$HARBOR_USER" --password-stdin harbor.external.prod.ascendro.io
              docker build -t $IMAGE_NAME .
              docker push "$IMAGE_NAME"
      - step:
          name: Deploy Staging
          trigger: manual
          image: node:20
          script:
            - |
              if [ -z "$PORTAINER_STAGING_WEBHOOK" ]; then
                echo "ERROR: PORTAINER_STAGING_WEBHOOK is not set!"
                exit 1
              fi

              if [ -z "$BRIDGE_STAGING" ]; then
                echo "ERROR: BRIDGE_STAGING is not set!"
                exit 1
              fi

              PAYLOAD=$(node -e "
                const idRe = /^[A-Za-z0-9-]{8,64}$/;

                const id = process.env.PORTAINER_STAGING_WEBHOOK;

                if (!id || !idRe.test(id)) {
                  console.error('Invalid or missing PORTAINER_STAGING_WEBHOOK');
                  process.exit(1);
                }

                process.stdout.write(JSON.stringify({ webhookIds: [id] }));
              ")
              export PAYLOAD

              SIG=$(node -e "
                const crypto = require('crypto');
                const payload = process.env.PAYLOAD;
                const secret = process.env.BRIDGE_STAGING;
                if (!secret) {
                  console.error('BRIDGE_STAGING is not set');
                  process.exit(1);
                }
                process.stdout.write(
                  crypto.createHmac('sha256', secret).update(payload, 'utf8').digest('hex')
                );
              ")

              curl -sS -X POST "https://devopsbridge.external.staging.ascendro.io/webhook/bitbucket/batch" \
                -H "Content-Type: application/json" \
                -H "X-Hub-Signature: sha256=$SIG" \
                -d "$PAYLOAD"

definitions:
  services:
    docker:
      memory: 3072
