name: Build Alpine RootFS and Docker Image (latest)

on:
  push:
    branches: 
      - main
    paths:
      - '!**/CHANGES.md'
      - '!**/build-info.json'
  schedule:
    - cron: '0 12 * * 0'  # Sunday at noon UTC

env:
  ALPINE_VERSION: v3.20
  TAG_NAME: latest
  IMAGE_NAME: gitea.fithwum.tech/fithwum/alpine-base
  OUTPUT_DIR: latest
  OUTPUT_TAR: latest/alpine-base.tar.gz

jobs:
  build-and-push:
    runs-on: vm-docker-build2
    outputs:
      tarball-updated: ${{ steps.set-output.outputs.tarball_updated }}
    steps:
      - name: Checkout repo
        uses: actions/checkout@v3

      - name: Build Alpine Base Image
        run: |
          docker build -t alpine-builder .
          mkdir -p latest
          container_id=$(docker create alpine-builder)
          docker cp "$container_id":/output/alpine-base.tar.gz ./latest/alpine-base.tar.gz
          docker rm "$container_id"

      - name: Show tarball
        run: ls -lh ${{ env.OUTPUT_TAR }}

      - name: Clone upload repo
        run: git clone https://gitea.fithwum.tech/fithwum/alpine-base.git upload-repo

      - name: Copy and push tarball
        run: |
          cp ${{ env.OUTPUT_TAR }} upload-repo/${{ env.OUTPUT_TAR }}
          cd upload-repo

          git config user.name "${{ secrets.GIT_USERNAME }}"
          git config user.email "${{ secrets.GIT_EMAIL }}"

          git remote set-url origin https://$GIT_USERNAME:${{ secrets.GIT_TOKEN }}@gitea.fithwum.tech/fithwum/alpine-base.git

          if git status --porcelain | grep .; then
            git add ${{ env.OUTPUT_TAR }}
            git commit -m "Update latest rootfs on $(date -u +'%Y-%m-%dT%H:%M:%SZ')"
            git push
            echo "tarball_updated=true" >> $GITHUB_ENV
          else
            echo "tarball_updated=false" >> $GITHUB_ENV
          fi

  push-docker:
    needs: build-and-push
    if: needs.build-and-push-rootfs.outputs.tarball-updated == 'true'
    runs-on: vm-docker-build2

    steps:
      - name: Build and push Docker image
        run: |
          echo "${{ secrets.DOCKER_PASSWORD }}" | docker login gitea.fithwum.tech -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin

      - name: Clone upload repo
        run: git clone https://gitea.fithwum.tech/fithwum/alpine-base.git upload-repo

      - name: Build and push Docker image
        run: |
          cd upload-repo
          docker buildx build \
            --file latest/Dockerfile \
            --platform linux/amd64 \
            -t "${{ env.IMAGE_NAME }}:${{ env.TAG_NAME }}" \
            --push .

  update-changelog:
    needs: push-docker
    runs-on: vm-docker-build2

    steps:
      - name: Clone repo with token auth
        run: |
          git clone https://${{ secrets.GIT_USERNAME }}:${{ secrets.GIT_TOKEN }}@gitea.fithwum.tech/fithwum/alpine-base.git upload-repo

      - name: Update CHANGES.md
        run: |
          cd upload-repo
          changelog="${{ env.OUTPUT_DIR }}/CHANGES.md"
          mkdir -p "$(dirname "$changelog")"
          touch "$changelog"

          last_commit=""
          if [ -f "${{ env.OUTPUT_DIR }}/build-info.json" ]; then
            last_commit=$(jq -r '.commit' "${{ env.OUTPUT_DIR }}/build-info.json")
          fi

          echo -e "\n## $(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "$changelog"

          if [ -n "$last_commit" ]; then
            git log "${last_commit}..HEAD" --pretty=format:"- %s (%an)" | head -n 10 >> "$changelog"
          else
            git log -n 10 --pretty=format:"- %s (%an)" >> "$changelog"
          fi

          git config user.name "${{ secrets.GIT_USERNAME }}"
          git config user.email "${{ secrets.GIT_EMAIL }}"

          if git status --porcelain | grep .; then
            git add "$changelog"
            git commit -m "Update changelog for latest"
            git push https://${{ secrets.GIT_USERNAME }}:${{ secrets.GIT_TOKEN }}@gitea.fithwum.tech/fithwum/alpine-base.git
          fi

  update-build-info:
    needs: update-changelog
    runs-on: vm-docker-build2

    steps:
      - name: Clone repo with token auth
        run: |
          git clone https://${{ secrets.GIT_USERNAME }}:${{ secrets.GIT_TOKEN }}@gitea.fithwum.tech/fithwum/alpine-base.git upload-repo

      - name: Generate build-info.json
        run: |
          cd upload-repo
          mkdir -p "${{ env.OUTPUT_DIR }}"

          image="${{ env.IMAGE_NAME }}:${{ env.TAG_NAME }}"
          size_bytes=$(docker image inspect "$image" --format='{{.Size}}')
          digest=$(docker inspect --format='{{index .RepoDigests 0}}' "$image")

          jq -n \
            --arg commit "$(git rev-parse HEAD)" \
            --arg tag "$image" \
            --arg digest "$digest" \
            --arg size "$(numfmt --to=iec-i --suffix=B $size_bytes)" \
            --argjson size_bytes "$size_bytes" \
            --arg time "$(date -u +'%Y-%m-%dT%H:%M:%SZ')" \
            '{
              commit: $commit,
              image_tag: $tag,
              digest: $digest,
              image_size: $size,
              image_size_bytes: $size_bytes,
              build_time: $time
            }' > "${{ env.OUTPUT_DIR }}/build-info.json"

      - name: Commit build-info.json
        run: |
          cd upload-repo
          git config user.name "${{ secrets.GIT_USERNAME }}"
          git config user.email "${{ secrets.GIT_EMAIL }}"
          git add "${{ env.OUTPUT_DIR }}/build-info.json"

          if git status --porcelain | grep .; then
            git commit -m "Update build-info for latest"
            git push https://${{ secrets.GIT_USERNAME }}:${{ secrets.GIT_TOKEN }}@gitea.fithwum.tech/fithwum/alpine-base.git

            git tag -d "build-latest" 2>/dev/null || true
            git tag "build-latest"
            git push https://${{ secrets.GIT_USERNAME }}:${{ secrets.GIT_TOKEN }}@gitea.fithwum.tech/fithwum/alpine-base.git --tags
          fi

