name: Deploy

on:
  push:
    branches: [main]
  schedule:
    - cron: '0 6 * * *'
  workflow_dispatch:

jobs:
  deploy:
    runs-on: self-hosted
    env:
      DEPLOY_DIR: /opt/websites/adrian-altner.de
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Sync to deploy directory
        run: |
          sudo rsync -a --delete \
            --exclude='.env' \
            --exclude='.env.production' \
            --exclude='.git/' \
            --exclude='node_modules/' \
            ./ "${DEPLOY_DIR}/"

      - name: Secret check
        env:
          WEBMENTION_TOKEN: ${{ secrets.WEBMENTION_TOKEN }}
          WEBMENTION_APP_TOKEN: ${{ secrets.WEBMENTION_APP_TOKEN }}
        run: |
          echo "WEBMENTION_TOKEN length: ${#WEBMENTION_TOKEN}"
          echo "WEBMENTION_APP_TOKEN length: ${#WEBMENTION_APP_TOKEN}"

      - name: Build image
        run: |
          cd "${DEPLOY_DIR}"
          sudo podman build \
            --no-cache \
            --build-arg WEBMENTION_TOKEN="${{ secrets.WEBMENTION_TOKEN }}" \
            -t localhost/adrian-altner.de:latest .

      - name: Restart service
        run: sudo systemctl restart podman-compose@adrian-altner.de.service

      - name: Prune
        run: |
          sudo podman container prune -f 2>/dev/null || true
          sudo podman image prune --external -f 2>/dev/null || true
          sudo podman image prune -f 2>/dev/null || true
          sudo podman builder prune -af 2>/dev/null || true

      - name: Send webmentions
        env:
          WEBMENTION_APP_TOKEN: ${{ secrets.WEBMENTION_APP_TOKEN }}
        run: |
          if [ -z "$WEBMENTION_APP_TOKEN" ]; then
            echo "No WEBMENTION_APP_TOKEN — skipping."
            exit 0
          fi
          for feed in rss.xml en/rss.xml; do
            curl -s -X POST "https://webmention.app/check?url=https://adrian-altner.de/${feed}&token=${WEBMENTION_APP_TOKEN}" \
              | grep -o '"status":"[^"]*"' || true
          done
