name: goreleaser

on:
  push:
    branches:
      - main

env:
  PRODUCT_VERSION: "1.11.3"

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - name: Set up Go
        uses: actions/setup-go@v2
        with:
          go-version: "1.23"
      - name: Setup Hugo
        uses: peaceiris/actions-hugo@v2
        with:
          hugo-version: '0.115.4'
          extended: true
      - name: Fetch dependencies
        run: |
          ./bin/fetch-deps.sh
      - name: Hugo Build
        run: hugo --minify
      - name: Garbagespeak Build
        run: |
          mkdir out
          CGO_ENABLED=0 go build -o "out/garbage-speak-${GITHUB_SHA}" server.go
      - name: S3 Sync
        uses: jakejarvis/s3-sync-action@v0.5.1
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.B2_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.B2_SECRET_ACCESS_KEY }}
          AWS_S3_BUCKET: "garbage-speak-application"
          AWS_REGION: "us-east-005"
          AWS_S3_ENDPOINT: "https://s3.us-east-005.backblazeb2.com "
          SOURCE_DIR: "out"
  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Tailscale login
        uses: tailscale/github-action@v2
        with:
          version: 1.76.6
          oauth-client-id: kexKXpQZxu11CNTRL
          oauth-secret: ${{ secrets.TS_OAUTH_SECRET }}
          tags: tag:github-action
        env:
          ADDITIONAL_ARGS: "--accept-dns"

      - name: Checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - name: Setup Nomad
        uses: hashicorp/setup-nomad@main
        with:
          version: ${{ env.PRODUCT_VERSION }}
      - name: Deploy nomad job
        run: |
          # Discover active Nomad server via Tailscale
          NOMAD_SERVER_IP=$(tailscale status --json | jq -r '.Peer[] | select(.Tags[]? == "tag:nomad-server") | select(.Online == true) | .TailscaleIPs[0]' | head -n1)
          echo "Using Nomad server: $NOMAD_SERVER_IP"
          export NOMAD_ADDR="http://${NOMAD_SERVER_IP}:4646"
          nomad job run -var version=${GITHUB_SHA} -var b2_access_key_id=${B2_ACCESS_KEY_ID} -var b2_secret_access_key=${B2_SECRET_ACCESS_KEY} job.nomad.hcl
        env:
          NOMAD_TOKEN: ${{ secrets.NOMAD_TOKEN }}
          B2_ACCESS_KEY_ID: ${{ secrets.B2_ACCESS_KEY_ID }}
          B2_SECRET_ACCESS_KEY: ${{ secrets.B2_SECRET_ACCESS_KEY }}
