name: Build
on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main
  workflow_dispatch:
  schedule:
    - cron: 0 0 * * 1

jobs:
  test:
    name: Build and Test
    runs-on: ubuntu-latest

    env:
      TEST_HOST: host.example.com
      TEST_REALM: EXAMPLE.COM
      TEST_USERNAME: test
      TEST_PASSWORD: password
      TEST_KEYTAB: ${{ github.workspace }}/testdata/test.keytab
      KRB5_CLIENT_KTNAME: ${{ github.workspace }}/testdata/test.keytab
      KRB5_CONFIG: ${{ github.workspace }}/testdata/krb5.conf
      KRB5_KTNAME: ${{ github.workspace }}/testdata/host.keytab

    steps:
      - name: Checkout
        uses: actions/checkout@v6

      - name: Set up Go
        uses: actions/setup-go@v6
        with:
          go-version-file: 'go.mod'

      - name: golangci-lint
        uses: golangci/golangci-lint-action@v9
        if: github.event_name == 'pull_request'
        with:
          only-new-issues: true

      - name: Install Kerberos client
        run: |
          sudo apt-get update
          sudo DEBIAN_FRONTEND=noninteractive apt-get install -yq libkrb5-dev krb5-user

      - name: Podman version
        id: podman
        shell: bash
        run: |
          echo "version=$(podman version | grep '^Version:' | tr -s ' ' | cut -d ' ' -f 2)" >>"${GITHUB_OUTPUT}"

      - name: Downgrade Docker
        if: steps.podman.outputs.version == '3.4.4'
        shell: bash
        run: |
          apt-cache madison docker.io
          sudo apt-get remove containerd.io
          sudo apt-get install docker.io=24.0.7-0ubuntu2~22.04.1

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

      - name: Build KDC image
        uses: docker/build-push-action@v7
        with:
          context: "{{defaultContext}}:testdata"
          load: true
          tags: kdc
          target: kdc
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Extract keytab
        uses: docker/build-push-action@v7
        with:
          context: "{{defaultContext}}:testdata"
          outputs: type=local,dest=testdata
          target: keytab

      - name: Pull containers into Podman
        run: |
          podman pull docker-daemon:kdc:latest

      - name: Create infrastructure
        run: |
          podman run -d \
            -v /etc/localtime:/etc/localtime:ro \
            -p 127.0.0.1:8088:8088 \
            -p 127.0.0.1:8088:8088/udp \
            -p 127.0.0.1:8464:8464 \
            -p 127.0.0.1:8464:8464/udp \
            --name kdc kdc
          echo $TEST_PASSWORD | KRB5_TRACE=/dev/stdout kinit ${TEST_USERNAME}@${TEST_REALM}

      - name: Test
        run: go test -v -coverprofile=cover.out ./...

      - name: Send coverage
        uses: shogo82148/actions-goveralls@v1
        with:
          path-to-profile: cover.out
