name: deploy-pangolin

on:
  push:
    branches: [main]
    paths:
      - 'deploy/**'
      - '.gitea/workflows/deploy.yml'
  workflow_dispatch:

jobs:
  deploy:
    # ⚠️ 改成你 NAS 上 act_runner 的实际 label(Gitea→Settings→Actions→Runners)
    runs-on: nas
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Ensure ssh/rsync
        run: |
          if ! command -v rsync >/dev/null || ! command -v ssh >/dev/null; then
            (command -v apt-get >/dev/null && apt-get update -y && apt-get install -y openssh-client rsync) \
            || (command -v apk >/dev/null && apk add --no-cache openssh-client rsync)
          fi

      - name: SSH 私钥(指向 EC2)
        run: |
          mkdir -p ~/.ssh && chmod 700 ~/.ssh
          printf '%s\n' "${{ secrets.EC2_SSH_KEY }}" > ~/.ssh/ec2_key
          chmod 600 ~/.ssh/ec2_key
          ssh-keyscan -H "${{ secrets.EC2_HOST }}" >> ~/.ssh/known_hosts 2>/dev/null || true

      - name: 同步 deploy/ 到 EC2(保留 secrets)
        run: |
          rsync -az \
            --exclude 'secrets' \
            --exclude 'singbox/config.json' \
            --exclude 'xray/config.json' \
            -e "ssh -i ~/.ssh/ec2_key -o StrictHostKeyChecking=accept-new" \
            deploy/ "${{ secrets.EC2_USER }}@${{ secrets.EC2_HOST }}:pangolin/"

      - name: 远程部署(免 root,幂等)
        run: |
          ssh -i ~/.ssh/ec2_key -o StrictHostKeyChecking=accept-new \
            "${{ secrets.EC2_USER }}@${{ secrets.EC2_HOST }}" \
            "export CF_API_TOKEN='${{ secrets.CF_API_TOKEN }}'; cd ~/pangolin && chmod +x scripts/*.sh && ./scripts/deploy.sh"
