name: "*** Deploy to Dev Cluster ***"

on:
  workflow_dispatch:

jobs:
  build_do_images:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2
        with:
          driver-opts: network=host

      - name: Login to Regsitry
        uses: docker/login-action@v2
        with:
          registry: ${{ secrets.DO_REGISTRY }}
          username: ${{ secrets.DO_API_TOKEN }}
          password: ${{ secrets.DO_API_TOKEN }}

      -
        name: Set Env Vars
        run: |
          echo VERSION=`cat version.txt` >> $GITHUB_ENV
          echo GIT_COMMIT_HASH=`git rev-parse --short HEAD` >> $GITHUB_ENV
          echo GIT_BRANCH_NAME=`git rev-parse --abbrev-ref HEAD` >> $GITHUB_ENV

      - name: Build Backend
        uses: docker/build-push-action@v3
        with:
          context: backend
          push: true
          tags: ${{ secrets.DO_REGISTRY_PATH }}/webrecorder/browsertrix-backend:latest
          cache-from: type=gha,scope=backend
          cache-to: type=gha,scope=backend,mode=max

      - name: Build Frontend
        uses: docker/build-push-action@v3
        with:
          context: frontend
          push: true
          build-args: |
            VERSION=${{ env.VERSION }}
            GIT_COMMIT_HASH=${{ env.GIT_COMMIT_HASH }}
            GIT_BRANCH_NAME=${{ env.GIT_BRANCH_NAME }}

          tags: ${{ secrets.DO_REGISTRY_PATH }}/webrecorder/browsertrix-frontend:latest
          cache-from: type=gha,scope=frontend
          cache-to: type=gha,scope=frontend,mode=max

      - name: Get Kubeconfig
        env:
          KUBECONFIG_DATA: ${{ secrets.KUBECONFIG_DATA }}
          DEV_VALUES: ${{ secrets.DEV_VALUES }}

        run: |
          printf "$KUBECONFIG_DATA" >> ./.kubeconfig
          chmod 400 ./.kubeconfig
          printf "$DEV_VALUES" >> ./dev-values.yaml

      - name: Install Kubectl
        uses: azure/setup-kubectl@v3

      - name: Install Helm
        uses: azure/setup-helm@v3
        with:
          version: 3.10.2

      - name: Start Cluster with Helm
        run: |
          KUBECONFIG=./.kubeconfig helm upgrade --install -f ./chart/values.yaml -f ./dev-values.yaml btrix ./chart/
