name: Build and Push Alpine RootFS and Docker Images

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

env:
  ALPINE_VERSIONS: "v3.18 v3.19 v3.20"
  IMAGE_REGISTRY: gitea.fithwum.tech
  IMAGE_ORG: fithwum
  IMAGE_REPO: alpine-base

jobs:
  build-and-upload-rootfs:
    runs-on: vm-docker-build2
    steps:
      - name: Checkout repo
        uses: actions/checkout@v3

      - name: Build and export Alpine rootfs archives
        run: |
          mkdir -p output
          for version in $ALPINE_VERSIONS; do
            echo "[INFO] Building Alpine $version rootfs"
            docker build --build-arg ALPINE_VERSION=$version -t alpine-builder:$version -f Dockerfile .

            mkdir -p output/$version
            cid=$(docker create alpine-builder:$version)
            docker cp "$cid":/output/alpine-${version}.tar.gz output/$version/
            docker rm "$cid"
          done

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

      - name: Copy archives to upload repo
        run: |
          for version in $ALPINE_VERSIONS; do
            mkdir -p upload-repo/$version
            cp output/$version/alpine-$version.tar.gz upload-repo/$version/
          done

      - name: Commit and push updated archives
        run: |
          cd upload-repo
          git config user.name "${{ secrets.GIT_USERNAME }}"
          git config user.email "${{ secrets.GIT_EMAIL }}"

          if git status --porcelain | grep .; then
            git add */alpine-$version.tar.gz
            git commit -m "Update Alpine rootfs $(date -u +'%Y-%m-%dT%H:%M:%SZ')"
            git push
          else
            echo "[INFO] No rootfs changes to commit."
          fi

  build-and-push-docker-images:
    needs: build-and-upload-rootfs
    runs-on: vm-docker-build2
    steps:
      - name: Clone upload repo
        run: git clone https://${{ secrets.GIT_USERNAME }}:${{ secrets.GIT_TOKEN }}@gitea.fithwum.tech/fithwum/alpine-base.git upload-repo

      - name: Generate Dockerfiles per version (if missing)
        run: |
          for version in $ALPINE_VERSIONS; do
            mkdir -p "upload-repo/$version"
            DOCKERFILE_PATH="upload-repo/$version/Dockerfile"

            if [[ -f "$DOCKERFILE_PATH" ]]; then
              echo "[INFO] Skipping existing $DOCKERFILE_PATH"
              continue
            fi

            printf '%s\n' \
              "FROM scratch" \
              "LABEL maintainer=\"fithwum\"" \
              "ADD alpine-$version.tar.gz /" \
              "CMD [\"/bin/sh\"]" > "$DOCKERFILE_PATH"

            echo "[INFO] Created $DOCKERFILE_PATH"
          done

      - name: Log in to Docker registry
        run: echo "${{ secrets.DOCKER_PASSWORD }}" | docker login ${{ env.IMAGE_REGISTRY }} -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin

      - name: Build and push Docker images
        run: |
          for version in $ALPINE_VERSIONS; do
            IMAGE="${{ env.IMAGE_REGISTRY }}/${{ env.IMAGE_ORG }}/${{ env.IMAGE_REPO }}:$version"
            echo "[INFO] Building and pushing $IMAGE"
            docker buildx build --platform linux/amd64 -t "$IMAGE" -f /$version/Dockerfile --push upload-repo/$version
          done

  generate-changelogs:
    needs: build-and-push-docker-images
    runs-on: vm-docker-build2
    steps:
      - name: Clone upload repo
        run: git clone https://${{ secrets.GIT_USERNAME }}:${{ secrets.GIT_TOKEN }}@gitea.fithwum.tech/fithwum/alpine-base.git upload-repo

      - name: Generate and push changelogs
        run: |
          cd upload-repo
          for version in $ALPINE_VERSIONS; do
            mkdir -p "$version"
            changelog="$version/CHANGES.md"
            touch "$changelog"

            last_commit=""
            if [ -f "$version/build-info.json" ]; then
              last_commit=$(jq -r '.commit' "$version/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
          done

          git config user.name "${{ secrets.GIT_USERNAME }}"
          git config user.email "${{ secrets.GIT_EMAIL }}"
          if git status --porcelain | grep .; then
            git add */CHANGES.md
            git commit -m "Update changelogs $(date -u +'%Y-%m-%dT%H:%M:%SZ')"
            git push
          fi

  generate-build-info:
    needs: generate-changelogs
    runs-on: vm-docker-build2
    steps:
      - name: Clone upload repo
        run: git clone https://${{ secrets.GIT_USERNAME }}:${{ secrets.GIT_TOKEN }}@gitea.fithwum.tech/fithwum/alpine-base.git upload-repo

      - name: Generate and commit build-info.json
        run: |
          cd upload-repo
          for version in $ALPINE_VERSIONS; do
            IMAGE="${{ env.IMAGE_REGISTRY }}/${{ env.IMAGE_ORG }}/${{ env.IMAGE_REPO }}:$version"
            digest=$(docker inspect --format='{{index .RepoDigests 0}}' "$IMAGE" 2>/dev/null || echo "unknown")
            size_bytes=$(docker image inspect "$IMAGE" --format='{{.Size}}' 2>/dev/null || echo "0")

            human_size=$(numfmt --to=iec-i --suffix=B $size_bytes)

            mkdir -p "$version"
            jq -n \
              --arg commit "$(git rev-parse HEAD)" \
              --arg image_tag "$IMAGE" \
              --arg digest "$digest" \
              --arg image_size "$human_size" \
              --argjson image_size_bytes "$size_bytes" \
              --arg build_time "$(date -u +'%Y-%m-%dT%H:%M:%SZ')" \
              '{
                commit: $commit,
                image_tag: $image_tag,
                digest: $digest,
                image_size: $image_size,
                image_size_bytes: $image_size_bytes,
                build_time: $build_time
              }' > "$version/build-info.json"
          done

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

          if git status --porcelain | grep .; then
            git add */build-info.json
            git commit -m "Update build-info $(date -u +'%Y-%m-%dT%H:%M:%SZ')"
            git push

            for version in $ALPINE_VERSIONS; do
              tag="build-$version"
              git tag -d "$tag" 2>/dev/null || true
              git tag "$tag"
              git push origin "$tag" --force
            done
          fi





















# name: Build Alpine RootFS and Docker Image (latest)

# on:
#   push:
#     branches: 
#       - main
#     paths:
#       - '.gitea/workflows/*.yml'
#       - '!**/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 repo with token auth
#         run: git clone https://${{ secrets.GIT_USERNAME }}:${{ secrets.GIT_TOKEN }}@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 repo with token auth
#         run: git clone https://${{ secrets.GIT_USERNAME }}:${{ secrets.GIT_TOKEN }}@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