# manual rollback
on:
  workflow_dispatch:
    inputs:
      steps:
        description: "How many releases to roll back (1 = previous)"
        default: "1"

jobs:
  rollback:
    runs-on: [ mainhost ]
    env:
      SSH_HOST: ${{ secrets.SSH_HOST }}
      SSH_USER: ${{ secrets.SSH_USER }}
      SSH_KEY_PATH: /home/gitea-runner/.ssh/id_ed25519
      SSH_OPTS: >-
        -F /dev/null -o IdentitiesOnly=yes -o IdentityAgent=none
        -o PreferredAuthentications=publickey -o PubkeyAuthentication=yes
        -o PasswordAuthentication=no -o NumberOfPasswordPrompts=0 -o BatchMode=yes
        -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o ConnectTimeout=20
        -o StrictHostKeyChecking=no
      APP_ROOT: /var/www/stellaamor
      SERVICE_RELOAD: "systemctl reload apache2 || true"

    steps:
      - name: Roll back symlink to an older release
        run: |
          set -euo pipefail
          APP="${{ env.APP_ROOT }}"
          RELEASES="${APP}/releases"
          CUR="${APP}/current"
          N="${{ github.event.inputs.steps || '1' }}"

          # pick target release (1=previous)
          TARGET="$(ls -1tr "${RELEASES}" | tail -n +"$((N+1))" | tail -n 1)"
          if [ -z "${TARGET}" ]; then
            echo "No release found to roll back to."; exit 1
          fi
          echo "Rolling back to: ${TARGET}"

          ssh $SSH_OPTS -i "$SSH_KEY_PATH" ${SSH_USER}@${SSH_HOST} "
            set -euo pipefail
            APP='${APP}'; RELEASES='${RELEASES}'; CUR='${CUR}'; TARGET='${TARGET}';
            [ -d \"\${RELEASES}/\${TARGET}\" ] || { echo 'Target release missing'; exit 1; }
            ln -sfn \"\${RELEASES}/\${TARGET}\" \"\${CUR}\"
            ${SERVICE_RELOAD} >/dev/null 2>&1 || true
          "
