name: Build and Deploy

on:
  push:
    branches: [main]

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version: "1.25"

      - name: Check formatting
        run: |
          unformatted=$(gofmt -l .)
          if [ -n "$unformatted" ]; then
            echo "Unformatted files:"
            echo "$unformatted"
            exit 1
          fi

      - name: Build
        run: CGO_ENABLED=0 go build -o podstalk .

      - name: Run tests
        run: go test ./...

      - name: Login to Gitea Container Registry
        env:
          CONTAINER_REGISTRY_TOKEN: ${{ secrets.CONTAINER_REGISTRY_TOKEN }}
        run: |
          if [ -z "$CONTAINER_REGISTRY_TOKEN" ]; then
            echo "CONTAINER_REGISTRY_TOKEN not set, skipping Docker publish"
            exit 0
          fi
          echo "$CONTAINER_REGISTRY_TOKEN" | docker login git.roo.lol -u ${{ github.actor }} --password-stdin

      - name: Build and push Docker image
        env:
          CONTAINER_REGISTRY_TOKEN: ${{ secrets.CONTAINER_REGISTRY_TOKEN }}
        run: |
          if [ -z "$CONTAINER_REGISTRY_TOKEN" ]; then
            echo "CONTAINER_REGISTRY_TOKEN not set, skipping Docker publish"
            exit 0
          fi
          docker build \
            -t git.roo.lol/${{ github.repository }}:latest \
            -t git.roo.lol/${{ github.repository }}:${{ github.sha }} \
            .
          docker push git.roo.lol/${{ github.repository }}:latest
          docker push git.roo.lol/${{ github.repository }}:${{ github.sha }}

      - name: Deploy to production
        env:
          DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }}
          DEPLOY_USER: ${{ vars.DEPLOY_USER }}
          DEPLOY_HOST: ${{ vars.DEPLOY_HOST }}
          DEPLOY_DIRECTORY: ${{ vars.DEPLOY_DIRECTORY }}
        run: |
          if [ -z "$DEPLOY_KEY" ] || [ -z "$DEPLOY_USER" ] || [ -z "$DEPLOY_HOST" ] || [ -z "$DEPLOY_DIRECTORY" ]; then
            [ -z "$DEPLOY_KEY" ] && echo "MISSING SECRET: DEPLOY_KEY"
            [ -z "$DEPLOY_USER" ] && echo "MISSING VAR: DEPLOY_USER"
            [ -z "$DEPLOY_HOST" ] && echo "MISSING VAR: DEPLOY_HOST"
            [ -z "$DEPLOY_DIRECTORY" ] && echo "MISSING VAR: DEPLOY_DIRECTORY"
            echo "Deploy secrets not fully set, skipping deployment"
            exit 0
          fi
          mkdir -p ~/.ssh
          echo "$DEPLOY_KEY" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          ssh -o StrictHostKeyChecking=accept-new -i ~/.ssh/deploy_key "$DEPLOY_USER@$DEPLOY_HOST" \
            "cd $DEPLOY_DIRECTORY && docker compose pull && docker compose down && docker compose up -d"
