# CI: immutability + Flyway validate (JDBC na staging / sdílenou DB). Deploy na main až po úspěchu.
# Job bez container: — hostovský docker + git (stejně jako deploy).
# Gitea secrets: EMS_CI_FLYWAY_URL (jdbc:postgresql://…/ems). Volitelně EMS_CI_FLYWAY_USER, EMS_CI_FLYWAY_PASSWORD.
# Runner: container.valid_volumes pro /var/run/docker.sock (viz docs/deployment-self-hosted.md).
#
# Spuštění deploye: push na main. Nepřidávat paralelně pull_request:closed — při merge by běžel deploy dvakrát.

name: CI and deploy

on:
  push:
    branches:
      - main
      - dev
      - feature/**
  pull_request:
  workflow_dispatch:

jobs:
  migration-check:
    runs-on: self-hosted
    steps:
      - name: Checkout
        env:
          TOKEN: ${{ github.token }}
        run: |
          set -eu
          su="${{ github.server_url }}"
          case "$su" in
            https://*) clone_url="https://oauth2:${TOKEN}@${su#https://}" ;;
            http://*) clone_url="http://oauth2:${TOKEN}@${su#http://}" ;;
            *) echo "unknown github.server_url: $su"; exit 1 ;;
          esac
          clone_url="${clone_url}/${{ github.repository }}.git"
          git init
          git remote add origin "$clone_url"
          git fetch --depth=64 origin "${{ github.sha }}"
          git checkout -qf FETCH_HEAD
          git remote set-branches origin 'main' || true
          git fetch --depth=64 origin main:refs/remotes/origin/main || true

      - name: Repo layout
        run: |
          test -f docker-compose.yml
          test -f deploy/docker-compose.yml
          test -x deploy/deploy.sh
          test -x scripts/ci_check_migration_immutability.sh
          test -x scripts/ci_flyway_validate_remote.sh

      - name: Migration immutability (vs PR base or main)
        env:
          PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
        run: |
          set -eu
          BASE='origin/main'
          if [ -n "${PR_BASE_SHA:-}" ]; then
            BASE="$PR_BASE_SHA"
            git fetch --no-tags --depth=256 origin "$BASE" || true
          fi
          ./scripts/ci_check_migration_immutability.sh "$BASE"

      - name: Flyway validate (remote DB)
        env:
          EMS_CI_FLYWAY_URL: ${{ secrets.EMS_CI_FLYWAY_URL }}
          EMS_CI_FLYWAY_USER: ${{ secrets.EMS_CI_FLYWAY_USER }}
          EMS_CI_FLYWAY_PASSWORD: ${{ secrets.EMS_CI_FLYWAY_PASSWORD }}
        run: ./scripts/ci_flyway_validate_remote.sh

  deploy:
    needs: migration-check
    if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
    runs-on: self-hosted
    steps:
      - name: Show execution context
        run: |
          whoami
          hostname
          pwd
          ls -ld /opt/ems-deploy

      - name: Run deploy script
        # Nejdřív aktualizovat checkout + ROOT kopii skriptu z repa (jinak by
        # opravy deploy.sh nikdy nedoputovaly na server — skript se spouští
        # z /opt/ems-deploy, ne z checkoutu). deploy.sh pak fetch/reset zopakuje
        # idempotentně.
        run: |
          git -c safe.directory=/opt/ems-deploy/app -C /opt/ems-deploy/app fetch origin
          git -c safe.directory=/opt/ems-deploy/app -C /opt/ems-deploy/app reset --hard origin/main
          install -m 0755 /opt/ems-deploy/app/deploy/deploy.sh /opt/ems-deploy/deploy.sh
          bash /opt/ems-deploy/deploy.sh

  # Alternativa: runner v Dockeru bez přístupu k hostu — odkomentovat a upravit SERVER + secrets.
  # deploy-ssh:
  #   runs-on: ubuntu-latest
  #   steps:
  #     - name: Deploy over SSH
  #       env:
  #         SSH_PRIVATE_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
  #       run: |
  #         mkdir -p ~/.ssh
  #         printf '%s\n' "$SSH_PRIVATE_KEY" > ~/.ssh/id_ed25519
  #         chmod 600 ~/.ssh/id_ed25519
  #         ssh -o StrictHostKeyChecking=yes -i ~/.ssh/id_ed25519 deploy@SERVER '/opt/ems-deploy/deploy.sh'
