# .forgejo/workflows/ci.yml
#
# Copy to YOUR APPLICATION REPO at .forgejo/workflows/ci.yml
# (not this infra repo — this is a template).
#
# What this does (on every push to main):
#   1. Run tests — fail here and nothing ships.
#   2. Build a Docker image and push it to the Forgejo built-in OCI registry.
#   3. Clone rock/deploy, bump the image tag in api/deployment.yaml, push the commit.
#   4. Argo CD sees the commit within 3 minutes and rolls out the new version.
#
# Required repo secrets (Forgejo UI → repo → Settings → Actions → Secrets):
#   REGISTRY_TOKEN  — ci-bot's package:write Forgejo API token
#   DEPLOY_TOKEN    — ci-bot's repo:write Forgejo API token (scoped to rock/deploy only)
#
# Prerequisites:
#   - ci-bot user created in Forgejo (see IAM section §11.5 of talos_version_control.html)
#   - ci-bot added as collaborator on rock/deploy with Write access
#   - Runner (cicd ns) is online and registered (Block 3 of build runbook)
#   - Talos nodes trust the homelab CA (Block 2 of build runbook)

on:
  push:
    branches: [main]

jobs:
  build-push-deploy:
    runs-on: docker

    steps:
      - uses: actions/checkout@v4

      # ── 1. Tests ────────────────────────────────────────────────────────────
      - name: test
        run: make test   # replace with your test command; failure stops the pipeline

      # ── 2. Build + push OCI image ───────────────────────────────────────────
      - name: build and push image
        env:
          REGISTRY: forgejo.forge.riotpiao.com
          OWNER: rock
        run: |
          REPO_NAME=${{ github.event.repository.name }}
          TAG=$(git rev-parse --short HEAD)
          IMAGE="${REGISTRY}/${OWNER}/${REPO_NAME}:${TAG}"

          echo "${{ secrets.REGISTRY_TOKEN }}" \
            | docker login "${REGISTRY}" -u "${OWNER}" --password-stdin

          docker build -t "${IMAGE}" .
          docker push "${IMAGE}"

          # Pass values to subsequent steps
          echo "TAG=${TAG}"          >> "$GITHUB_ENV"
          echo "IMAGE=${IMAGE}"      >> "$GITHUB_ENV"
          echo "REPO_NAME=${REPO_NAME}" >> "$GITHUB_ENV"

      # ── 3. Bump image tag in the deploy repo ────────────────────────────────
      # This is the ONLY write operation CI has on the cluster side.
      # Argo CD notices the commit and rolls out the new image.
      - name: bump deploy repo
        env:
          REGISTRY: forgejo.forge.riotpiao.com
          OWNER: rock
        run: |
          git clone \
            "https://ci-bot:${{ secrets.DEPLOY_TOKEN }}@${REGISTRY}/${OWNER}/deploy.git" \
            /tmp/deploy

          TARGET_FILE="/tmp/deploy/${REPO_NAME}/deployment.yaml"

          sed -i \
            "s|${REGISTRY}/${OWNER}/${REPO_NAME}:.*|${IMAGE}|" \
            "${TARGET_FILE}"

          git -C /tmp/deploy \
            -c user.name="ci-bot" \
            -c user.email="ci-bot@forgejo.forge.riotpiao.com" \
            commit -am "${REPO_NAME}: deploy ${TAG}"

          git -C /tmp/deploy push
