name: Continuous Integration

on:
  schedule:
    - cron: "0 7 * * *"
  push:
    branches:
      - main
      - master
    tags:
      - '*'
  pull_request:
    branches:
      - main
      - master

jobs:
  go-build-and-test:
    runs-on: ubuntu-latest
    name: "Run go tests"
    steps:
      - uses: actions/checkout@v4

      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.24.2'
          check-latest: true

      - name: Cache Go modules
        uses: actions/cache@v3
        with:
          path: |
            ~/go/pkg/mod
            ~/.cache/go-build
          key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
          restore-keys: |
            ${{ runner.os }}-go-

      - name: Build
        run: go build -v

      - name: Test
        run: go test -v

  build-with-xcaddy-and-push:
    runs-on: ubuntu-latest
    name: "Build with xcaddy and push to GHCR"
    permissions:
      contents: read
      packages: write
    env:
      REGISTRY: ghcr.io
      IMAGE_NAME: ${{ github.repository }}
    steps:
      - uses: actions/checkout@v4

      - name: Log in to GHCR (tags only)
        if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Set image tags
        id: tags
        run: |
          if [ "${{ github.event_name }}" = "push" ] && [[ "${{ github.ref }}" == refs/tags/* ]]; then
            {
              echo "tags<<EOF"
              echo "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.ref_name }}"
              echo "${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest"
              echo "EOF"
            } >> $GITHUB_OUTPUT
          else
            echo "tags=caddy-cloudflare:local" >> $GITHUB_OUTPUT
          fi

      - name: Build Docker image with xcaddy and optionally push to GHCR
        uses: docker/build-push-action@v6
        with:
          context: .
          push: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') }}
          tags: ${{ steps.tags.outputs.tags }}
