name: Publish
on:
  workflow_call:
    inputs:
      nightly:
        default: false
        required: false
        type: boolean
      version:
        required: true
        type: string
      target_commitish:
        required: true
        type: string
    secrets:
      ARCHIVE_REPO_TOKEN:
        required: false

permissions:
  contents: write

jobs:
  publish:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - uses: actions/download-artifact@v3
      - uses: actions/setup-python@v4
        with:
          python-version: "3.10"

      - name: Generate release notes
        run: |
          cat >> ./RELEASE_NOTES << EOF
          #### A description of the various files are in the [README](https://github.com/yt-dlp/yt-dlp#release-files)
          ---
          <details><summary><h3>Changelog</h3></summary>
          $(python ./devscripts/make_changelog.py -vv)
          </details>
          EOF
          echo "**This is an automated nightly pre-release build**" >> ./PRERELEASE_NOTES
          cat ./RELEASE_NOTES >> ./PRERELEASE_NOTES
          echo "Generated from: https://github.com/${{ github.repository }}/commit/${{ inputs.target_commitish }}" >> ./ARCHIVE_NOTES
          cat ./RELEASE_NOTES >> ./ARCHIVE_NOTES

      - name: Archive nightly release
        env:
          GH_TOKEN: ${{ secrets.ARCHIVE_REPO_TOKEN }}
          GH_REPO: ${{ vars.ARCHIVE_REPO }}
        if: |
          inputs.nightly && env.GH_TOKEN != '' && env.GH_REPO != ''
        run: |
          gh release create \
            --notes-file ARCHIVE_NOTES \
            --title "yt-dlp nightly ${{ inputs.version }}" \
            ${{ inputs.version }} \
            artifact/*

      - name: Prune old nightly release
        if: inputs.nightly && !vars.ARCHIVE_REPO
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          gh release delete --yes --cleanup-tag "nightly" || true
          git tag --delete "nightly" || true
          sleep 5  # Enough time to cover deletion race condition

      - name: Publish release${{ inputs.nightly && ' (nightly)' || '' }}
        env:
          GH_TOKEN: ${{ github.token }}
        if: (inputs.nightly && !vars.ARCHIVE_REPO) || !inputs.nightly
        run: |
          gh release create \
            --notes-file ${{ inputs.nightly && 'PRE' || '' }}RELEASE_NOTES \
            --target ${{ inputs.target_commitish }} \
            --title "yt-dlp ${{ inputs.nightly && 'nightly ' || '' }}${{ inputs.version }}" \
            ${{ inputs.nightly && '--prerelease "nightly"' || inputs.version }} \
            artifact/*
