name: Publish a Release
on:
  workflow_dispatch:
    inputs:
      version:
        description: 'Version without leading "v" (1.0, 2.3.4, 0.1.0-pre1)'
        required: true
        default: ''
      image_tags:
        description: 'Extra docker image tags ("latest,test")'
        required: true
        default: 'latest,release'
jobs:
  publish:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    permissions:
      contents: write
      packages: write
    steps:
    - name: Ensure version does not start with 'v'
      uses: actions/github-script@v7
      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@v4
      with:
        submodules: true
    - name: Cache data/sources
      uses: ./.github/cache-sources-action
    - uses: actions/setup-java@v4
      with:
        java-version: '21'
        distribution: 'temurin'
        cache: 'maven'
        server-id: ossrh
        server-username: MAVEN_USERNAME
        server-password: MAVEN_PASSWORD

    - 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@v7
      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 planetiler-dist/target/*with-deps.jar planetiler.jar
    - run: sha256sum planetiler.jar > planetiler.jar.sha256
    - run: md5sum planetiler.jar > planetiler.jar.md5
    - name: Install GPG Private Key
      run: |
        echo -n "${{ secrets.OSSRH_GPG_SECRET_KEY }}" | base64 --decode | gpg --batch --import
    - name: Create Release
      uses: softprops/action-gh-release@v2
      with:
        fail_on_unmatched_files: true
        tag_name: v${{ github.event.inputs.version }}
        draft: true
        files: |
          planetiler.jar*
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    - run: ./scripts/push-release.sh ${{ github.event.inputs.version }}
      env:
        GITHUB_ACTOR: ${{ github.actor }}
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        IMAGE_TAGS: ${{ github.event.inputs.image_tags }}
        MAVEN_USERNAME: ${{ secrets.OSSRH_USERNAME }}
        MAVEN_PASSWORD: ${{ secrets.OSSRH_PASSWORD }}
        OSSRH_GPG_SECRET_KEY_PASSWORD: ${{ secrets.OSSRH_GPG_SECRET_KEY_PASSWORD }}
