name: Deploy specified artifact as a branch
on:
  workflow_call:
    inputs:
      environment:
        description: Environment to publish under
        required: true
        type: string
      artifact_name:
        description: Artifact name
        required: true
        type: string
      target_branch:
        description: Target branch
        required: true
        type: string
      commit_message:
        description: Commit message
        required: true
        type: string
permissions: {}
jobs:
  deploy-artifact-as-branch:
    environment:
      name: ${{ inputs.environment }}
      url: ${{ github.server_url }}/${{ github.repository }}/tree/${{ inputs.target_branch }}
    runs-on: ubuntu-latest
    permissions:
      contents: write # for actions/checkout and to push branch
    steps:
      - name: Checkout `${{ inputs.target_branch }}` branch
        uses: actions/checkout@v3
        with:
          ref: ${{ inputs.target_branch }}

      - name: Remove existing files first
        run: git rm -r .

      - uses: actions/download-artifact@v3
        with:
          name: ${{ inputs.artifact_name }}

      - name: Publish target branch
        run: |
          git add -A
          if git diff --staged --quiet; then
            echo 'Nothing to publish'
          else
            git config user.name 'GitHub Action Script'
            git config user.email 'please@open.issue'

            git commit -a -m "$COMMIT_MESSAGE"
            git push
            echo 'Pushed'
          fi
        env:
          TARGET_BRANCH: ${{ inputs.target_branch }}
          COMMIT_MESSAGE: ${{ inputs.commit_message }}