name: Publish a Release
on:
  workflow_dispatch:
    inputs:
      version:
        description: 'Version without leading "v" (1.0, 2.3.4, 0.2-alpha, 5.9-beta.3)'
        required: true
        default: ''
      image_tags:
        description: 'Extra docker image tags ("latest,test")'
        required: true
        default: 'latest'
jobs:
  publish:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    permissions:
      contents: write
      packages: write
    steps:
      - name: Ensure version does not start with 'v'
        uses: actions/github-script@v5
        with:
          github-token: ${{ github.token }}
          script: |
            version = context.payload.inputs.version;
            if (/^v/.test(version)) throw new Error("Bad version number: " + version)
      - uses: actions/checkout@v2
      - name: Cache data/sources
        uses: ./.github/cache-sources-action
      - uses: actions/setup-java@v2
        with:
          java-version: '17'
          distribution: 'temurin'
          cache: 'maven'

      - name: Check tag does not exist yet
        run: if git rev-list "v${{ github.event.inputs.version }}"; then echo "Tag already exists. Aborting the release process."; exit 1; fi

      - run: ./scripts/set-versions.sh "${{ github.event.inputs.version }}"
      - run: ./scripts/build-release.sh
      - run: ./scripts/test-release.sh "${{ github.event.inputs.version }}"
      - name: Create tag
        uses: actions/github-script@v5
        with:
          github-token: ${{ github.token }}
          script: |
            github.rest.git.createRef({
              owner: context.repo.owner,
              repo: context.repo.repo,
              ref: "refs/tags/v${{ github.event.inputs.version }}",
              sha: context.sha
            })
      - run: mv flatmap-dist/target/*with-deps.jar flatmap.jar
      - run: sha256sum flatmap.jar > flatmap.jar.sha256
      - run: md5sum flatmap.jar > flatmap.jar.md5
      - name: Log in to the Container Registry
        uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Create Release
        uses: softprops/action-gh-release@v1
        with:
          fail_on_unmatched_files: true
          tag_name: v${{ github.event.inputs.version }}
          draft: true
          files: |
            flatmap.jar*
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      - run: ./scripts/push-release.sh ${{ github.event.inputs.version }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          IMAGE_TAGS: ${{ github.event.inputs.image_tags }}
