name: Koori-ERP-Deploy-System

on:
  push:
    branches:
      - demo
      - main

jobs:
  # --- 1. Demo 環境部署 (103 本機) ---
  deploy-demo:
    if: github.ref == 'refs/heads/demo'
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Code
        uses: actions/checkout@v3
        with:
          github-server-url: http://192.168.0.103:3000
          repository: ${{ github.repository }}

      - name: Step 1 - Push Code to Demo
        run: |
          apt-get update && apt-get install -y rsync openssh-client
          mkdir -p ~/.ssh
          echo "${{ secrets.DEMO_SSH_KEY }}" > ~/.ssh/id_rsa_demo
          chmod 600 ~/.ssh/id_rsa_demo
          rsync -avz --delete \
            --exclude='.git' \
            --exclude='node_modules' \
            --exclude='vendor' \
            --exclude='storage' \
            --exclude='.env' \
            --exclude='public/build' \
            -e "ssh -i ~/.ssh/id_rsa_demo -o StrictHostKeyChecking=no" \
            ./ amba@192.168.0.103:/home/amba/star-erp/
          rm ~/.ssh/id_rsa_demo

      # 2. 檢查是否需要重建容器（只有 Dockerfile 或 compose.yaml 變動時才重建）
      - name: Step 2 - Check if Rebuild Needed
        id: check_rebuild
        uses: appleboy/ssh-action@master
        with:
          host: 192.168.0.103
          port: 22
          username: amba
          key: ${{ secrets.DEMO_SSH_KEY }}
          script: |
            cd /home/amba/star-erp
            # 檢查最近的 commit 是否包含 Dockerfile 或 compose.yaml 的變更
            if git diff --name-only HEAD~1 HEAD 2>/dev/null | grep -qE '(Dockerfile|compose\.yaml|docker-compose\.yaml)'; then
              echo "REBUILD_NEEDED=true"
            else
              echo "REBUILD_NEEDED=false"
            fi

      # 3. 啟動或重建容器（根據檢查結果決定是否加 --build）
      - name: Step 3 - Container Up & Health Check
        uses: appleboy/ssh-action@master
        with:
          host: 192.168.0.103
          port: 22
          username: amba
          key: ${{ secrets.DEMO_SSH_KEY }}
          script: |
            cd /home/amba/koori-erp
            chown -R 1000:1000 .
            
            # 檢查是否需要重建
            if git diff --name-only HEAD~1 HEAD 2>/dev/null | grep -qE '(Dockerfile|compose\.yaml|docker-compose\.yaml)'; then
              echo "🔄 偵測到 Docker 相關檔案變更，執行完整重建..."
              WWWGROUP=1000 WWWUSER=1000 docker compose up -d --build --wait
            else
              echo "⚡ 無 Docker 檔案變更，僅重載服務..."
              # 確保容器正在運行（若未運行則啟動）
              if ! docker ps --format '{{.Names}}' | grep -q 'koori-erp-laravel'; then
                echo "容器未運行，正在啟動..."
                WWWGROUP=1000 WWWUSER=1000 docker compose up -d --wait
              else
                echo "容器已運行，跳過 docker compose，直接進行程式碼部署..."
              fi
            fi
            
            echo "容器狀態：" && docker ps --filter "name=koori-erp-laravel"


      - name: Step 4 - Composer & NPM Build
        uses: appleboy/ssh-action@master
        with:
          host: 192.168.0.103
          port: 22
          username: amba
          key: ${{ secrets.DEMO_SSH_KEY }}
          script: |
           docker exec -u 1000:1000 -w /var/www/html star-erp-laravel sh -c "
            # 1. 後端依賴 (Demo 環境建議加上 --no-interaction 避免卡住)
            composer install --no-dev --optimize-autoloader --no-interaction &&
            
            # 2. 前端編譯
            npm install &&
            npm run build &&
            
            # 3. Laravel 初始化與優化
            php artisan migrate --force &&
            php artisan db:seed --force &&
            php artisan optimize:clear &&
            php artisan optimize &&
            php artisan view:cache
           "
           docker exec star-erp-laravel chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache

  # --- 2. 正式環境部署 (erp.koori.tw:2224) ---
  deploy-production:
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Code
        uses: actions/checkout@v3
        with:
          github-server-url: http://192.168.0.103:3000 
          repository: ${{ github.repository }}

      - name: Step 1 - Push Code to Production
        run: |
          apt-get update && apt-get install -y rsync openssh-client
          mkdir -p ~/.ssh
          echo "${{ secrets.PROD_SSH_KEY }}" > ~/.ssh/id_rsa_prod
          chmod 600 ~/.ssh/id_rsa_prod
          rsync -avz --delete \
            --exclude='.git' \
            --exclude='.env' \
            --exclude='node_modules' \
            --exclude='vendor' \
            --exclude='public/build' \
            -e "ssh -p 2224 -i ~/.ssh/id_rsa_prod -o StrictHostKeyChecking=no" \
            ./ root@erp.koori.tw:/var/www/star-erp/
          rm ~/.ssh/id_rsa_prod


      # 2. 檢查是否需要重建容器（只有 Dockerfile 或 compose.yaml 變動時才重建）
      - name: Step 2 - Check if Rebuild Needed
        id: check_rebuild_prod
        uses: appleboy/ssh-action@master
        with:
          host: erp.koori.tw
          port: 2224
          username: root
          key: ${{ secrets.PROD_SSH_KEY }}
          script: |
            cd /var/www/star-erp
            # [Patch] 修正正式機 Nginx Proxy 配置 (對應外部 SSL/OpenResty)
            sed -i "s/- '8080:8080'/- '80:80'\n            - '8080:8080'/" compose.yaml
            sed -i "s/demo-proxy.conf/prod-proxy.conf/" compose.yaml

            # 檢查最近的 commit 是否包含 Dockerfile 或 compose.yaml 的變更
            if git diff --name-only HEAD~1 HEAD 2>/dev/null | grep -qE '(Dockerfile|compose\.yaml|docker-compose\.yaml)'; then
              echo "REBUILD_NEEDED=true"
            else
              echo "REBUILD_NEEDED=false"
            fi

      # 3. 啟動或重建容器（根據檢查結果決定是否加 --build）
      - name: Step 3 - Container Up & Health Check
        uses: appleboy/ssh-action@master
        with:
          host: erp.koori.tw
          port: 2224
          username: root
          key: ${{ secrets.PROD_SSH_KEY }}
          script: |
            cd /var/www/star-erp
            chown -R 1000:1000 .
            
            # 檢查是否需要重建
            if git diff --name-only HEAD~1 HEAD 2>/dev/null | grep -qE '(Dockerfile|compose\.yaml|docker-compose\.yaml)'; then
              echo "🔄 偵測到 Docker 相關檔案變更，執行完整重建..."
              WWWGROUP=1000 WWWUSER=1000 docker compose up -d --build --wait
            else
              echo "⚡ 無 Docker 檔案變更，僅重載服務..."
              # 確保容器正在運行（若未運行則啟動）
              if ! docker ps --format '{{.Names}}' | grep -q 'star-erp-laravel'; then
                echo "容器未運行，正在啟動..."
                WWWGROUP=1000 WWWUSER=1000 docker compose up -d --wait
              else
                echo "容器已運行，跳過 docker compose，直接進行程式碼部署..."
              fi
            fi
            
            echo "容器狀態：" && docker ps --filter "name=star-erp-laravel"

            docker exec -u 1000:1000 -w /var/www/html star-erp-laravel sh -c "
              composer install --no-dev --optimize-autoloader &&
              npm install &&
              npm run build

              php artisan migrate --force &&
              php artisan optimize:clear &&
              php artisan optimize &&
              php artisan view:cache
            "
            docker exec star-erp-laravel chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache