name: Build Docker Linux ARM64

on:
  push:
    branches:
      - main

jobs:
  build-docker-linux-arm64:
    runs-on: [self-hosted, linux, arm64, docker]
    steps:
      - name: Install packages
        run: apk add --no-cache git curl wget unzip bash nodejs npm docker

      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
        
      - name: Setup Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Get Repository Name
        id: get_repo
        run: |
          REPO_LC="${GITHUB_REPOSITORY,,}" 
          echo "REPO_LC=$REPO_LC" >> $GITHUB_ENV
          echo "Repo: $REPO_LC"
          
      - name: Build version
        shell: bash
        run: |
          LAST_TAG=$(git describe --tags --abbrev=0)
          
          if [[ -z "${LAST_TAG:-}" ]]; then
            echo "No tag found"
            exit 1
          fi
          
          COMMIT_COUNT=$(git rev-list $LAST_TAG..HEAD --count)
          
          if [[ "$LAST_TAG" == *-* ]]; then
            TEMP_LAST_TAG ="${LAST_TAG%-*}"
            VERSION="${TEMP_LAST_TAG}-nightly.${COMMIT_COUNT}"
          else
            VERSION="$[LAST_TAG}-nightly.${COMMIT_COUNT}"
          fi
          
          echo "LAST_TAG=$LAST_TAG" >> "$GITHUB_ENV"
          echo "COMMIT_COUNT=$COMMIT_COUNT" >> "$GITHUB_ENV"
          echo "VERSION=$VERSION" >> "$GITHUB_ENV"
          
          echo "Last tag: $LAST_TAG"
          echo "Commit count: $COMMIT_COUNT"
          echo "Final version: $VERSION"
          
      - name: Build Linux ARM64 Docker Image
        run: |
          docker build \
            -t gitea.penry.de/${{ env.REPO_LC }}:nightly \
            --build-arg VERSION=${{ env.VERSION }} \
            .
      
      - name: Login to own image registry
        uses: docker/login-action@v3
        with:
          registry: gitea.penry.de
          username: ${{ secrets.REGISTRY_USER }}
          password: ${{ secrets.REGISTRY_PASSWORD }}
      
      - name: Push Images
        run: |
          docker push gitea.penry.de/${{ env.REPO_LC }}:nightly

      - name: Save Docker Image to Tar
        run: docker save -o CouchLog-Linux-ARM64-Docker-Image.tar gitea.penry.de/${{ env.REPO_LC }}:nightly

      - name: Upload Artifact
        uses: actions/upload-artifact@v3
        with:
          name: CouchLog-Linux-ARM64-Docker-Image
          path: CouchLog-Linux-ARM64-Docker-Image.tar
          if-no-files-found: error
          retention-days: 5