# Announce every GitHub release on social media with the Ampost CLI.
#
# Setup (guide: https://ampost.io/how-to/post-to-social-media-from-github-actions):
#   1. Save this file as .github/workflows/post-release-to-social.yml in your repository.
#   2. Settings > Secrets and variables > Actions:
#      - secret   AMPOST_API_KEY   an API key from https://ampost.io/app/settings/api-keys
#      - variable AMPOST_PLATFORMS comma-separated networks, e.g. bluesky,threads,discord
#   3. Publish a release, or run the workflow by hand from the Actions tab.
#
# The CLI (https://ampost.io/docs/tools/cli) is installed from npm: ampost-cli 0.1.x.

name: Post release to social media

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      text:
        description: Post text
        required: true

permissions: {}

jobs:
  post:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - name: Install the Ampost CLI
        run: npm install -g ampost-cli@0.1

      - name: Post to social media with Ampost
        env:
          AMPOST_API_KEY: ${{ secrets.AMPOST_API_KEY }}
          AMPOST_PLATFORMS: ${{ vars.AMPOST_PLATFORMS }}
          # Passed through env, never pasted into the script, so a release name can't inject shell code.
          RELEASE_NAME: ${{ github.event.release.name || github.event.release.tag_name }}
          RELEASE_URL: ${{ github.event.release.html_url }}
          RELEASE_ID: ${{ github.event.release.id }}
          MANUAL_TEXT: ${{ github.event.inputs.text }}
          REPOSITORY: ${{ github.repository }}
          RUN_ID: ${{ github.run_id }}
        run: |
          set -euo pipefail
          if [ -z "${AMPOST_API_KEY}" ]; then echo "::error::Add the AMPOST_API_KEY secret"; exit 1; fi
          if [ -z "${AMPOST_PLATFORMS}" ]; then echo "::error::Add the AMPOST_PLATFORMS variable, e.g. bluesky,threads"; exit 1; fi

          if [ -n "${RELEASE_ID}" ]; then
            TEXT="${REPOSITORY} ${RELEASE_NAME} is out: ${RELEASE_URL}"
            # One key per release: a re-run of this job never posts the release twice.
            set -- --link "${RELEASE_URL}" --idempotency-key "release-${REPOSITORY}-${RELEASE_ID}"
          else
            TEXT="${MANUAL_TEXT}"
            set -- --idempotency-key "manual-${REPOSITORY}-${RUN_ID}"
          fi

          # The text goes in on stdin, so a text that starts with "-" is not read as an option.
          # --wait waits for every network's result: the job fails (exit 10) if one refused the post.
          printf '%s' "$TEXT" | ampost post --text-file - -p "$AMPOST_PLATFORMS" --wait --wait-timeout 300 "$@"
