name: Release

on:
  push:
    tags:
      - "389-ds-base-*"
  workflow_dispatch:
    inputs:
      version:
        description: Specify tag to generate a tarball
        required: true
      skip-audit-ci:
        description: Skip npx --yes audit-ci
        type: boolean
        default: false

permissions:
  actions: read
  packages: read
  contents: write

jobs:
  build:
    runs-on: ubuntu-latest
    container:
      image: quay.io/389ds/ci-images:test
    steps:
      - name: Get the version
        id: get_version
        run: |
            echo "version=${VERSION}" >> $GITHUB_OUTPUT
        env:
          VERSION: ${{ github.event.inputs.version || github.ref_name }}

      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: ${{ steps.get_version.outputs.version }}

      - name: Check if the tagged commit belongs to a valid branch
        run: |
          git config --global --add safe.directory "$GITHUB_WORKSPACE"
          COMMIT=$(git rev-parse HEAD)
          BRANCHES=$(git branch -a --contains $COMMIT | grep -v 'HEAD detached at')
          if [ -n "$BRANCHES" ]; then
              echo "Tagged commit $COMMIT belongs to the following branch(es):"
              echo "$BRANCHES"
          else
              echo "Tagged commit $COMMIT does not belong to any branch."
              exit 1
          fi

      - name: Create tarball
        run: |
          git config --global --add safe.directory "$GITHUB_WORKSPACE"
          if [ "${{ github.event.inputs.skip-audit-ci }}" = "true" ]; then
              export SKIP_AUDIT_CI=1
          fi
          TAG=${{ steps.get_version.outputs.version }} make -f rpm.mk dist-bz2

      - name: Upload tarball
        uses: actions/upload-artifact@v4
        with:
          name: ${{ steps.get_version.outputs.version }}.tar.bz2
          path: ${{ steps.get_version.outputs.version }}.tar.bz2

      - name: Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ steps.get_version.outputs.version }}
          files: |
            ${{ steps.get_version.outputs.version }}.tar.bz2
