name: Build Docker Image
run-name: ${{ gitea.actor }} building ${{ gitea.ref_name }}
on:
  push:
    branches:
      - main
      - dev

jobs:
  Docker-Build:
    runs-on: ubuntu-latest
    steps:
      - name: Clone Repository
        uses: actions/checkout@v4

      - name: Build docker image
        run: docker build -t umbrella .

      - name: Store tag date
        run: |
          TAG=$(date +%Y%m%d_%H%M)_${{ gitea.ref_name }}
          echo $TAG > /tmp/tag
          echo Using '"'$TAG'"' as tag.

      - name: Tag image for upload
        run: |
          TAG=$(cat /tmp/tag)
          docker tag umbrella ${{ secrets.REGISTRY_PATH }}/umbrella:${{ gitea.ref_name }}
          docker tag umbrella ${{ secrets.REGISTRY_PATH }}/umbrella:$TAG

      - name: Login to registry
        uses: docker/login-action@v2
        with:
          registry: ${{ secrets.REGISTRY_PATH }}
          username: ${{ secrets.REGISTRY_USER }}
          password: ${{ secrets.REGISTRY_PASS }}

      - name: Push to registry
        run: |
          TAG=$(cat /tmp/tag)
          docker push ${{ secrets.REGISTRY_PATH }}/umbrella:${{ gitea.ref_name }}
          docker push ${{ secrets.REGISTRY_PATH }}/umbrella:$TAG

      - name: Restart umbrella.srsoftware.de
        if: github.ref == 'refs/heads/dev'
        run: |
          curl -X POST -H "Authorization: Bearer ${{ secrets.ELDORADO_MAKE_BEARER }}" -d umbrella_25_start https://make.eldorado.srsoftware.de/launch

  Clean-Registry:
    runs-on: ubuntu-latest
    steps:
      - name: Get tag list
        run: |
          TAGS="$(curl -s -u "${{ secrets.REGISTRY_USER }}:${{ secrets.REGISTRY_PASS }}" https://${{ secrets.REGISTRY_PATH }}/v2/umbrella/tags/list | jq -r ".tags[]")"
          COUNT=$(echo "$TAGS" | wc -l)
          if [ $COUNT -gt 10 ]; then
            REMAIN=$((COUNT - 10))
            echo "$TAGS" | head -n $REMAIN > /tmp/old_tags
          else
            echo less than 10 tags, skipping cleanup
            echo "" > /tmp/old_tags
          fi

      - name: Remove tags
        run: |
          cat /tmp/old_tags | while read TAG; do
            if [ -n "$TAG" ]; then
              DIGEST=$(curl -u "${{ secrets.REGISTRY_USER }}:${{ secrets.REGISTRY_PASS }}" -sS -H 'Accept: application/vnd.docker.distribution.manifest.v2+json' -o /dev/null -w '%header{Docker-Content-Digest}' https://${{ secrets.REGISTRY_PATH }}/v2/umbrella/manifests/$TAG)
              if [ -n "$DIGEST" ]; then
                echo about to delete $TAG
                curl -u "${{ secrets.REGISTRY_USER }}:${{ secrets.REGISTRY_PASS }}" -sS -X DELETE https://${{ secrets.REGISTRY_PATH }}/v2/umbrella/manifests/$DIGEST
              else
                echo failed to get digest for $TAG
              fi
            fi
          done
