name: Build Docker Image - Latest

on:
  workflow_dispatch:
    inputs:
      create_release:
        description: Create or update the Gitea release for this version
        required: true
        default: true
        type: boolean

env:
  REGISTRY: docker.lechner-systems.at
  IMAGE_NAME: lechnersystems/maintenance

jobs:
  docker:
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Read version
        id: version
        shell: bash
        run: |
          version="$(git rev-parse --short=12 HEAD)"

          if [[ ! "$version" =~ ^[0-9a-f]{12}$ ]]; then
            echo "Invalid git hash version: $version" >&2
            exit 1
          fi

          echo "value=$version" >> "$GITEA_OUTPUT"
          echo "docker_tag=$version" >> "$GITEA_OUTPUT"
          echo "release_tag=v$version" >> "$GITEA_OUTPUT"

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

      - name: Log in to registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ secrets.DOCKER_REGISTRY_USERNAME }}
          password: ${{ secrets.DOCKER_REGISTRY_PASSWORD }}

      - name: Build and push latest image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          provenance: false
          build-args: |
            APP_VERSION=${{ gitea.sha }}
            VCS_REF=${{ gitea.run_number }}
          tags: |
            ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
          labels: |
            org.opencontainers.image.version=${{ gitea.sha }}
            org.opencontainers.image.revision=${{ gitea.run_number }}
            org.opencontainers.image.source=${{ gitea.repositoryUrl }}

      - name: Create Gitea release
        if: ${{ inputs.create_release }}
        env:
          GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
          GITEA_API_URL: ${{ gitea.api_url }}
          GITEA_REPOSITORY: ${{ gitea.repository }}
          GITEA_SHA: ${{ gitea.sha }}
          RELEASE_TAG: ${{ steps.version.outputs.release_tag }}
        shell: bash
        run: |
          releases_url="$GITEA_API_URL/repos/$GITEA_REPOSITORY/releases"
          auth_header="Authorization: token $GITEA_TOKEN"
          previous_tag="$(curl --fail --silent --show-error --header "$auth_header" "$releases_url?limit=100" | jq -r --arg tag "$RELEASE_TAG" '[.[] | select(.draft == false and .prerelease == false and .tag_name != $tag)][0].tag_name // empty')"

          if [ -n "$previous_tag" ]; then
            commit_messages="$(git log --reverse --format='- %s' "${previous_tag}..${GITEA_SHA}")"
            full_changelog="${{ gitea.server_url }}/${GITEA_REPOSITORY}/compare/${previous_tag}...${RELEASE_TAG}"
          else
            commit_messages="$(git log --reverse --format='- %s' "${GITEA_SHA}")"
            full_changelog=""
          fi

          if [ -z "$commit_messages" ]; then
            commit_messages="- No commits since the previous release"
          fi

          {
            echo "## Changes"
            echo
            printf "%s\n" "$commit_messages"
            echo
            if [ -n "$full_changelog" ]; then
              echo "**Full Changelog**: ${full_changelog}"
            fi
          } > release-notes.md

          payload="$(jq -Rs --arg tag "$RELEASE_TAG" --arg target "$GITEA_SHA" '{tag_name: $tag, target_commitish: $target, name: $tag, body: ., draft: false, prerelease: false}' release-notes.md)"
          status="$(curl --silent --show-error --output release.json --write-out '%{http_code}' --header "$auth_header" "$releases_url/tags/$RELEASE_TAG")"

          if [ "$status" = 200 ]; then
            release_id="$(jq -r '.id' release.json)"
            curl --fail-with-body --silent --show-error --request PATCH --header "$auth_header" --header 'Content-Type: application/json' --data "$payload" "$releases_url/$release_id"
          elif [ "$status" = 404 ]; then
            curl --fail-with-body --silent --show-error --request POST --header "$auth_header" --header 'Content-Type: application/json' --data "$payload" "$releases_url"
          else
            cat release.json
            exit 1
          fi
