name: star-cloud-deploy-production

on:
  push:
    branches:
      - main

jobs:
  deploy-production:
    runs-on: [ubuntu-latest, prod]
    steps:
      - name: Checkout Code
        uses: actions/checkout@v3

      - name: Step 0 - Prepare Environment & Sync Configs
        run: |
          # 1. 確保結構正確
          mkdir -p docker/emqx

          # 2. 檢查並清理宿主機 (Host) 上被 Docker 誤建為目錄的檔案
          # 生產環境路徑為 ~/star-cloud (對應絕對路徑 /home/twsystem1003/star-cloud)
          docker run --rm -v /home/twsystem1003/star-cloud:/target busybox sh -c "
            if [ -d /target/.env ]; then echo 'Removing .env directory on host'; rm -rf /target/.env; fi
            if [ -d /target/docker/emqx/acl.conf ]; then echo 'Removing acl.conf directory on host'; rm -rf /target/docker/emqx/acl.conf; fi
          "

          # 3. 從宿主機載入持久化的 .env 檔案
          docker run --rm -v /home/twsystem1003/star-cloud:/data:ro busybox cat /data/.env > .env || cp .env.example .env

          # 4. 將 Runner 最新 Checkout 的設定檔同步至宿主機持久區
          docker run --rm -v /home/twsystem1003/star-cloud:/target busybox mkdir -p /target/docker/emqx
          cat docker/emqx/acl.conf | docker run -i --rm -v /home/twsystem1003/star-cloud:/target busybox sh -c "cat > /target/docker/emqx/acl.conf"

      - name: Step 1 - Ensure Existing Containers Are Running
        run: |
          for container in \
            star-cloud-mysql \
            star-cloud-redis \
            star-cloud-emqx
          do
            if ! docker inspect "${container}" >/dev/null 2>&1; then
              echo ">>> Required container is missing: ${container}"
              exit 1
            fi

            echo ">>> Ensuring ${container} is running..."
            docker start "${container}" >/dev/null
          done

          for container in star-cloud-mysql star-cloud-redis star-cloud-emqx; do
            echo ">>> Waiting for ${container} to become healthy..."

            for i in $(seq 1 60); do
              status=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "${container}" 2>/dev/null || echo "missing")

              if [ "${status}" = "healthy" ]; then
                echo ">>> ${container} is healthy."
                break
              fi

              if [ "${i}" -eq 60 ]; then
                echo ">>> ${container} did not become healthy. Current status: ${status}"
                docker logs --tail 80 "${container}" || true
                exit 1
              fi

              sleep 2
            done
          done

          for container in \
            star-cloud-laravel \
            star-cloud-queue \
            star-cloud-mqtt-worker \
            star-cloud-mqtt-gateway
          do
            if ! docker inspect "${container}" >/dev/null 2>&1; then
              echo ">>> Required container is missing: ${container}"
              exit 1
            fi

            echo ">>> Ensuring ${container} is running..."
            docker start "${container}" >/dev/null
          done

      - name: Step 2 - Deploy Code
        run: |
          echo ">>> Syncing code to star-cloud-laravel..."
          tar --exclude='.git' --exclude='node_modules' --exclude='vendor' \
              --exclude='storage' --exclude='bootstrap/cache' \
              -cf /tmp/deploy.tar . || [ $? -le 1 ]

          docker exec -i star-cloud-laravel tar -xf - -C /var/www/html/ < /tmp/deploy.tar
          rm -f /tmp/deploy.tar

          # 生產環境使用 1001:1001
          docker exec star-cloud-laravel sh -c "
            chown -R 1001:1001 /var/www/html &&
            mkdir -p /.npm && chown -R 1001:1001 /.npm &&
            rm -rf /var/www/html/node_modules
          "

      - name: Step 3 - Composer & NPM & Initialization
        run: |
          docker exec -u 1001:1001 -w /var/www/html star-cloud-laravel sh -c "
            composer install --no-dev --optimize-autoloader --no-interaction &&
            npm install &&
            npm run build &&
            php artisan migrate --force &&
            php artisan storage:link &&
            php artisan optimize:clear &&
            php artisan optimize &&
            php artisan view:cache &&
            php artisan queue:restart &&
            php artisan db:seed --class=RoleSeeder --force &&
            php artisan db:seed --class=AdminUserSeeder --force
          "
          docker exec star-cloud-laravel chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache

      - name: Step 4 - Restart Long-running Workers
        run: |
          docker restart star-cloud-mqtt-worker
          echo "✅ MQTT Worker 已重啟"

      - name: Step 5 - Cleanup
        run: docker image prune -f --filter "until=168h"
