stages:
    - staging
    - production

.deploy_template: &deploy_template
    image:
        name: php:8.3-cli
        entrypoint: ['']
    before_script:
        # Install dependencies
        - apt-get update -qy
        - apt-get install -qy openssh-client git curl rsync

        # Install nvm and Node
        - curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
        - export NVM_DIR="$HOME/.nvm"
        - . "$NVM_DIR/nvm.sh"
        - nvm install 20
        - nvm use 20

        # Install Deployer
        - curl -LO https://github.com/deployphp/deployer/releases/download/v7.5.12/deployer.phar
        - mv deployer.phar /usr/local/bin/dep
        - chmod +x /usr/local/bin/dep

        # Secure SSH configuration with environment-specific known hosts
        - mkdir -p ~/.ssh
        - eval $(ssh-agent -s)
        - echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add -
        - echo "$SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
        - chmod 644 ~/.ssh/known_hosts

        # Build theme assets
        - cd web/app/themes/ebook-viewer
        - npm install
        - npm run build
        - cd -

    script:
        # Encode authentication credentials in base64
        - ACF_USERNAME_B64=$(echo -n "$ACF_USERNAME" | base64)
        - ACF_PASSWORD_B64=$(echo -n "$ACF_PASSWORD" | base64)
        # Deploy to staging environment
        - |
            dep deploy $CI_ENVIRONMENT_NAME -vvv \
              --option acf_username_b64="$ACF_USERNAME_B64" \
              --option acf_password_b64="$ACF_PASSWORD_B64"

deploy_staging:
    <<: *deploy_template
    stage: staging
    environment:
        name: staging
    resource_group: staging
    rules:
        - if: $CI_COMMIT_BRANCH == "main" && $CI_DEPLOY_FREEZE == null

deploy_production:
    <<: *deploy_template
    stage: production
    environment:
        name: production
    resource_group: production
    rules:
        - if: $CI_COMMIT_BRANCH == "main" && $CI_DEPLOY_FREEZE == null
          when: manual
    needs:
        - deploy_staging
