name: Deploy

on:
  push:
    branches: [main]

env:
  REGISTRY: git.kimchi
  IMAGE: git.kimchi/tas/major_tom
  NAMESPACE: jnr-web
  DEPLOYMENT: jnr-web

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        run: |
          git config --global http.https://git.kimchi.sslVerify false
          git clone --depth 1 https://${{ secrets.REGISTRY_USER }}:${{ secrets.REGISTRY_PASSWORD }}@git.kimchi/tas/major_tom.git .

      - name: Debug registry auth
        run: |
          curl -s -D- http://git.kimchi/v2/ | head -15
          TOKEN=$(curl -s "http://git.kimchi/v2/token?service=container_registry&scope=repository:tas/major_tom:push,pull" -u "${{
          secrets.REGISTRY_USER }}:${{ secrets.REGISTRY_PASSWORD }}" | jq -r .token)
          echo "Token received: ${TOKEN:0:20}..."
          curl -s -D- -H "Authorization: Bearer $TOKEN" http://git.kimchi/v2/tas/major_tom/tags/list | head -15

      - name: Build and push container image
        run: |
          set -ex

          IMAGE_TAG="${{ env.IMAGE }}:sha-${GITHUB_SHA::8}"
          IMAGE_LATEST="${{ env.IMAGE }}:latest"

          buildah bud --tls-verify=false -f Containerfile -t "$IMAGE_TAG" -t "$IMAGE_LATEST" .

          CREDS="${{ secrets.REGISTRY_USER }}:${{ secrets.REGISTRY_PASSWORD }}"

          echo "=== buildah push tag ==="
          buildah push --tls-verify=false --creds "$CREDS" "$IMAGE_TAG"

          echo "=== buildah push latest ==="
          buildah push --tls-verify=false --creds "$CREDS" "$IMAGE_LATEST"

          echo "IMAGE_TAG=$IMAGE_TAG" >> "$GITHUB_ENV"

      - name: Restart deployment on k3s
        run: |
          mkdir -p ~/.kube
          echo "${{ secrets.KUBECONFIG }}" > ~/.kube/config
          chmod 600 ~/.kube/config

          POD_NAME=$(kubectl get pods -l app=jnr-web -n jnr-web -o jsonpath='{.items[0].metadata.name}')
          echo "Deleting running pod" "$POD_NAME"
          kubectl delete pod $POD_NAME -n jnr-web