name: Publish templates

on:
  workflow_call:
    secrets:
      VITE_TEMPLATE_REPO_SSH_DEPLOY_KEY:
        required: true
      NEXTJS_TEMPLATE_REPO_SSH_DEPLOY_KEY:
        required: true

env:
  CI: 1
  PRINT_GITHUB_ANNOTATIONS: 1

defaults:
  run:
    shell: bash

jobs:
  publish_vite:
    name: 'Vite'
    timeout-minutes: 15
    runs-on: ubuntu-latest-16-cores-open

    steps:
      - name: Check out code
        uses: actions/checkout@v3

      - name: Substitute the latest published version of tldraw
        run: |
          export TEMPLATE=vite NPM_TAG=latest && \
          npm view tldraw dist-tags --json | jq -r ".$NPM_TAG" > /tmp/latest_tldraw && \
          cp "templates/$TEMPLATE/package.json" /tmp/template_package.json && \
          jq --tab --arg latest_tldraw "$(< /tmp/latest_tldraw)" '.dependencies."tldraw" |= $latest_tldraw' /tmp/template_package.json > "templates/$TEMPLATE/package.json"

      - name: Push vite template to tldraw/vite-template
        uses: cpina/github-action-push-to-another-repository@07c4d7b3def0a8ebe788a8f2c843a4e1de4f6900 # v1.7.2
        env:
          SSH_DEPLOY_KEY: ${{ secrets.VITE_TEMPLATE_REPO_SSH_DEPLOY_KEY }}
        with:
          source-directory: 'templates/vite'
          destination-github-username: 'tldraw'
          destination-repository-name: 'vite-template'
          user-email: dan+github.actions@tldraw.com
          target-branch: main

  publish_next:
    name: 'Next.js'
    timeout-minutes: 15
    runs-on: ubuntu-latest-16-cores-open

    steps:
      - name: Check out code
        uses: actions/checkout@v3

      - name: Substitute the latest published version of tldraw
        run: |
          export TEMPLATE=nextjs NPM_TAG=latest && \
          npm view tldraw dist-tags --json | jq -r ".$NPM_TAG" > /tmp/latest_tldraw && \
          cp "templates/$TEMPLATE/package.json" /tmp/template_package.json && \
          jq --tab --arg latest_tldraw "$(< /tmp/latest_tldraw)" '.dependencies."tldraw" |= $latest_tldraw' /tmp/template_package.json > "templates/$TEMPLATE/package.json"

      - name: Push next.js template to tldraw/nextjs-template
        uses: cpina/github-action-push-to-another-repository@07c4d7b3def0a8ebe788a8f2c843a4e1de4f6900 # v1.7.2
        env:
          SSH_DEPLOY_KEY: ${{ secrets.NEXTJS_TEMPLATE_REPO_SSH_DEPLOY_KEY }}
        with:
          source-directory: 'templates/nextjs'
          destination-github-username: 'tldraw'
          destination-repository-name: 'nextjs-template'
          user-email: dan+github.actions@tldraw.com
          target-branch: main
