name: Deploy

on:
  push:
    branches:
      - main
  workflow_dispatch:

jobs:
  deploy:
    runs-on: host

    steps:
      - name: Show context
        shell: bash
        run: |
          set -euxo pipefail
          whoami
          hostname
          pwd

      - name: Prepare clean deploy checkout
        shell: bash
        run: |
          set -euxo pipefail
          DEPLOY_DIR="/home/adminko/ticket-system-deploy"
          REPO_URL="gitea-internal:openit/ticket-system.git"

          if [ ! -d "${DEPLOY_DIR}/.git" ]; then
            rm -rf "${DEPLOY_DIR}"
            git clone "${REPO_URL}" "${DEPLOY_DIR}"
          fi

          git -C "${DEPLOY_DIR}" remote set-url origin "${REPO_URL}"
          git -C "${DEPLOY_DIR}" fetch --prune origin
          git -C "${DEPLOY_DIR}" reset --hard origin/main

      - name: Link runtime files
        shell: bash
        run: |
          set -euxo pipefail
          DEPLOY_DIR="/home/adminko/ticket-system-deploy"

          ln -sfn /home/adminko/ticket-system/data "${DEPLOY_DIR}/data"
          ln -sfn /home/adminko/ticket-system/infra/.env "${DEPLOY_DIR}/infra/.env"

      - name: Rebuild and restart
        shell: bash
        run: |
          set -euxo pipefail
          cd /home/adminko/ticket-system-deploy/infra
          docker compose up -d --build

      - name: Show services
        shell: bash
        run: |
          set -euxo pipefail
          cd /home/adminko/ticket-system-deploy/infra
          docker compose ps
