name: Deploy (stellaamor)

on:
  push:
    branches: [ "main" ]

jobs:
  deploy:
    runs-on: [ mainhost ]  # must match your runner label (e.g. mainhost:host)
    env:
      SSH_HOST: ${{ secrets.SSH_HOST }}
      SSH_USER: ${{ secrets.SSH_USER }}
      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/api.stellaamor
      UPLOADS_DIR: uploads
      KEEP_N: "5"
      HEALTH_URL: https://api.stellaamor.com/
      SERVICE_RELOAD: "systemctl reload apache2 || true"
      SSH_KEY_PATH: /home/gitea-runner/.ssh/id_ed25519


    steps:
      - name: Checkout (pure git)
        run: |
          git init
          git remote add origin "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY"
          git fetch --depth=1 origin "$GITHUB_SHA"
          git checkout -q "$GITHUB_SHA"

      - name: SSH smoke test
        run: ssh $SSH_OPTS -i "$SSH_KEY_PATH" ${SSH_USER}@${SSH_HOST} true

      - name: Upload & activate atomically
        run: |
          set -euo pipefail
          REL="$(date -u +%Y%m%d-%H%M%SZ)-${{ github.sha }}"
          echo "REL=$REL" >> $GITHUB_ENV
          TAR="/tmp/${REL}.tar.gz"
          APP="${{ env.APP_ROOT }}"
          SHARED="${APP}/shared"
          RELEASES="${APP}/releases"
          CUR="${APP}/current"
          UPLOADS="${{ env.UPLOADS_DIR }}"

          tar -czf "$TAR" --exclude-vcs --exclude='./node_modules' --exclude="./${UPLOADS}" --exclude='./release' .
          mkdir -p release && mv "$TAR" "release/${REL}.tar.gz"

          ssh $SSH_OPTS -i "$SSH_KEY_PATH" ${SSH_USER}@${SSH_HOST} \
            "set -e; install -d -m 755 ${RELEASES} ${SHARED} ${SHARED}/${UPLOADS}"

          scp -O $SSH_OPTS -vvv -i "$SSH_KEY_PATH" "release/${REL}.tar.gz" ${SSH_USER}@${SSH_HOST}:/tmp/${REL}.tar.gz

          ssh $SSH_OPTS -i "$SSH_KEY_PATH" ${SSH_USER}@${SSH_HOST} '
            set -euo pipefail
            REL="'${REL}'"; APP="'${APP}'"; SHARED="'${SHARED}'"; RELEASES="'${RELEASES}'"; CUR="'${CUR}'"; UPLOADS="'${UPLOADS}'";
            NEW="${RELEASES}/${REL}"
            mkdir -p "${NEW}"
            tar -xzf "/tmp/${REL}.tar.gz" -C "${NEW}" && rm -f "/tmp/${REL}.tar.gz"
            rm -rf "${NEW}/${UPLOADS}" && ln -s "${SHARED}/${UPLOADS}" "${NEW}/${UPLOADS}"
            [ -f "${SHARED}/.env" ] && ln -sf "${SHARED}/.env" "${NEW}/.env" || true
            printf "sha=%s\nbuilt_at=%s\n" "'${{ github.sha }}'" "$(date -u +%FT%TZ)" > "${NEW}/RELEASE"
            PREV="$(readlink -f "${CUR}" || true)"
            ln -sfn "${NEW}" "${CUR}"
            '"${{ env.SERVICE_RELOAD }}"' >/dev/null 2>&1 || true
            if command -v curl >/dev/null 2>&1; then
              curl -fsS --max-time 5 "'"${{ env.HEALTH_URL }}"'" >/dev/null || {
                echo "Health check failed, rolling back..."
                [ -n "${PREV}" ] && ln -sfn "${PREV}" "${CUR}" && '"${{ env.SERVICE_RELOAD }}"' >/dev/null 2>&1 || true
                exit 1
              }
            fi
            cd "${RELEASES}" && ls -1tr | head -n -'${{ env.KEEP_N }}' | xargs -r -I{} rm -rf "{}"
          '
