name: Deploy Static Sites

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        run: |
          git clone --depth=1 --branch=${{ github.ref_name }} https://gitea.airlabs.art/${{ github.repository }}.git .

      - name: Setup SSH
        run: |
          mkdir -p ~/.ssh
          printf '%s\n' '${{ secrets.INTERNAL_SERVER_SSH_KEY }}' > ~/.ssh/id_rsa
          chmod 600 ~/.ssh/id_rsa
          ssh-keyscan -H 118.196.70.19 >> ~/.ssh/known_hosts 2>/dev/null

      - name: Sync files to server
        run: |
          ssh root@118.196.70.19 "rm -rf /data/static-sites/* && mkdir -p /data/static-sites"

          for dir in */; do
            case "$dir" in
              .gitea/|.git/|k8s/) continue ;;
            esac
            echo "上传 $dir ..."
            scp -r "$dir" root@118.196.70.19:/data/static-sites/
          done

          echo "✓ 文件同步完成"

      - name: Auto generate and apply Ingress
        run: |
          # 收集所有项目目录名
          PROJECTS=""
          for dir in */; do
            case "$dir" in
              .gitea/|.git/|k8s/) continue ;;
            esac
            name="${dir%/}"
            PROJECTS="$PROJECTS $name"
          done

          # 生成 Ingress YAML
          cat > /tmp/ingress.yaml <<'HEADER'
          apiVersion: networking.k8s.io/v1
          kind: Ingress
          metadata:
            name: static-sites-ingress
            annotations:
              kubernetes.io/ingress.class: "traefik"
              cert-manager.io/cluster-issuer: "letsencrypt-prod"
          spec:
            tls:
          HEADER

          # 生成 TLS 段
          for name in $PROJECTS; do
            cat >> /tmp/ingress.yaml <<EOF
            - hosts:
              - ${name}.airlabs.art
              secretName: ${name}-tls
          EOF
          done

          # 生成 rules 段
          echo "    rules:" >> /tmp/ingress.yaml
          for name in $PROJECTS; do
            cat >> /tmp/ingress.yaml <<EOF
            - host: ${name}.airlabs.art
              http:
                paths:
                - path: /
                  pathType: Prefix
                  backend:
                    service:
                      name: static-sites
                      port:
                        number: 80
          EOF
          done

          echo "--- 生成的 Ingress ---"
          cat /tmp/ingress.yaml

          # 上传并 apply
          scp /tmp/ingress.yaml root@118.196.70.19:/tmp/ingress.yaml
          ssh root@118.196.70.19 "kubectl apply -f /tmp/ingress.yaml"

          echo "✓ Ingress 已自动更新"

      - name: Verify
        run: |
          ssh root@118.196.70.19 "
            echo '=== 站点文件 ==='
            ls -la /data/static-sites/
            echo ''
            echo '=== Ingress ==='
            kubectl get ingress static-sites-ingress
            echo ''
            echo '=== 证书 ==='
            kubectl get certificate
          "
