# ============================================================
# CETERIS Connect SPC-PUSH - Bitbucket Pipelines
# Tests pytest + Deploiement Staging
# ============================================================

image: python:3.12-slim

definitions:
  caches:
    pip:
      key:
        files:
          - requirements.txt
      path: /root/.cache/pip

  steps:
    - step: &test-step
        name: Tests pytest
        caches:
          - pip
        script:
          - pip install -r requirements.txt --quiet
          - python -m pytest tests/ -v --tb=short -m "not selenium" --junitxml=test-results.xml
        artifacts:
          - test-results.xml

    - step: &create-pr-step
        name: Create PR dev → master
        image: alpine:3.19
        script:
          - apk add --no-cache curl
          - |
            echo "Creation PR dev -> master..."
            HTTP_CODE=$(curl -s -o /tmp/pr_response.txt -w "%{http_code}" \
              -X POST \
              -u "nicephore.allaglo@jupitech.fr:$BB_APP_PASSWORD" \
              -H "Content-Type: application/json" \
              "https://api.bitbucket.org/2.0/repositories/$BITBUCKET_REPO_FULL_NAME/pullrequests" \
              -d '{
                "title": "Merge dev (build #'"$BITBUCKET_BUILD_NUMBER"')",
                "source": {"branch": {"name": "dev"}},
                "destination": {"branch": {"name": "master"}},
                "description": "PR auto-generee apres succes des tests (pipeline #'"$BITBUCKET_BUILD_NUMBER"').\n\nCommit: '"$BITBUCKET_COMMIT"'",
                "close_source_branch": false
              }')
            if [ "$HTTP_CODE" = "201" ]; then
              echo "PR creee avec succes"
            elif [ "$HTTP_CODE" = "409" ]; then
              echo "PR deja existante - rien a faire"
            elif [ "$HTTP_CODE" = "400" ]; then
              echo "Pas de changements a merger (branches identiques) - OK"
            else
              echo "Erreur creation PR (HTTP $HTTP_CODE):"
              cat /tmp/pr_response.txt
              exit 1
            fi

    - step: &deploy-staging-step
        name: Deploy to Staging
        deployment: staging
        script:
          - apt-get update && apt-get install -y openssh-client
          - mkdir -p ~/.ssh
          - echo "$STAGING_SSH_KEY" | base64 -d > ~/.ssh/id_rsa
          - chmod 600 ~/.ssh/id_rsa
          - ssh-keyscan -H $STAGING_SERVER_IP >> ~/.ssh/known_hosts
          - ssh -i ~/.ssh/id_rsa -o StrictHostKeyChecking=no $STAGING_SSH_USER@$STAGING_SERVER_IP "export GIT_USER=jupitechfr && export GIT_TOKEN='$BB_APP_PASSWORD' && cd $STAGING_DEPLOY_ROOT && bash deploy-staging.sh spc-push"

pipelines:
  default:
    - step: *test-step

  branches:
    dev:
      - step: *test-step
      - step: *create-pr-step
    master:
      - step: *deploy-staging-step

  custom:
    daily-tests:
      - step: *test-step
