name: dogfood

on:
  push:
    branches:
      - main
    paths:
      - "dogfood/**"
  # Uncomment these lines when testing with CI.
  # pull_request:
  #   paths:
  #     - "dogfood/**"
  workflow_dispatch:

jobs:
  deploy_image:
    runs-on: ubuntu-latest
    steps:
      - name: Get branch name
        id: branch-name
        uses: tj-actions/branch-names@v6.5

      - name: "Branch name to Docker tag name"
        id: docker-tag-name
        run: |
          tag=${{ steps.branch-name.outputs.current_branch }}
          # Replace / with --, e.g. user/feature => user--feature.
          tag=${tag//\//--}
          echo "tag=${tag}" >> $GITHUB_OUTPUT

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v2

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2

      - name: Login to DockerHub
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_PASSWORD }}

      - name: Build and push
        uses: docker/build-push-action@v4
        with:
          context: "{{defaultContext}}:dogfood"
          push: true
          tags: "codercom/oss-dogfood:${{ steps.docker-tag-name.outputs.tag }},codercom/oss-dogfood:latest"
          cache-from: type=registry,ref=codercom/oss-dogfood:latest
          cache-to: type=inline
  deploy_template:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Get short commit SHA
        id: vars
        run: echo "sha_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
      - name: "Install latest Coder"
        run: |
          curl -L https://coder.com/install.sh | sh
        # env:
        #   VERSION: 0.x
      - name: "Push template"
        run: |
          coder templates push $CODER_TEMPLATE_NAME --directory $CODER_TEMPLATE_DIR --yes --name=$CODER_TEMPLATE_VERSION
        env:
          # Consumed by Coder CLI
          CODER_URL: https://dev.coder.com
          CODER_SESSION_TOKEN: ${{ secrets.CODER_SESSION_TOKEN }}
          # Template source & details
          CODER_TEMPLATE_NAME: ${{ secrets.CODER_TEMPLATE_NAME }}
          CODER_TEMPLATE_VERSION: ${{ steps.vars.outputs.sha_short }}
          CODER_TEMPLATE_DIR: ./dogfood
