name: "rpm-delivery"
description: "Deliver rpm packages"
inputs:
  module_name:
    description: "The package module name"
    required: true
  distrib:
    description: "The distribution used for packaging"
    required: true
  version:
    description: "Centreon packaged major version"
    required: true
  cache_key:
    description: "The cached package key"
    required: true
  stability:
    description: "The package stability (stable, testing, unstable)"
    required: true
  artifactory_token:
    description: "Artifactory token"
    required: true
  release_type:
    description: "Type of release (hotfix, release)"
    required: true
  is_cloud:
    description: "Release context (cloud or not cloud)"
    required: true
  delivery_type:
    description: "Delivery to feature or standard repository"
    required: true
  centreon_technique_pat:
    description: "Token used to handle delivery."
    required: true

runs:
  using: "composite"
  steps:
    - name: Use cache RPM files
      uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
      with:
        path: ./*.rpm
        key: ${{ inputs.cache_key }}
        fail-on-cache-miss: true

    - uses: jfrog/setup-jfrog-cli@ff5cb544114ffc152db9cea1cd3d5978d5074946 # v4.5.11
      env:
        JF_URL: https://packages.centreon.com
        JF_ACCESS_TOKEN: ${{ inputs.artifactory_token }}

    - if: inputs.delivery_type == 'feature'
      name: Create a rpm feature repository
      shell: bash
      env:
        JF_URL: https://packages.centreon.com
        JF_ACCESS_TOKEN: ${{ inputs.artifactory_token }}
      run: |
        set -eu
        . .version
        major_version=$(grep -E "MAJOR" .version | cut -d '=' -f2)
        feature_ticket=$(echo "${{ github.event.pull_request.head.ref }}" | grep -oE 'MON-[0-9]+')
        echo "[INFO] Creating a rpm feature repository if it does not exist"

        curl -X POST \
            -H "Authorization: Bearer ${{ inputs.centreon_technique_pat }}" \
            -H "Accept: application/vnd.github.v3+json" \
            https://api.github.com/repos/centreon/delivery-tooling/dispatches \
            -d "$(jq -n \
              --arg major_version "$major_version" \
              --arg repo_type "feature" \
              --arg feature_ticket "$feature_ticket" \
              '{
                event_type: "create-feature-repositories",
                client_payload: {
                  major_version: $major_version,
                  repo_type: $repo_type,
                  feature_ticket: $feature_ticket
                }
              }'
            )"

        response=""
        attempt=0
        until [[ $(echo "$response" | tr -d '\n' | tail -c 3) -eq 200 || $attempt -ge 40 ]]; do
          attempt=$(( attempt+1 ))
          echo "[INFO] Checking if the feature repository has been created... [ATTEMPT $attempt]"
          response=$(curl \
            --write-out "%{http_code}" \
            --request GET \
            --url "${{ env.JF_URL }}/artifactory/api/v2/repositories/rpm-standard-feature-$feature_ticket" \
            --header "Authorization: Bearer ${{ env.JF_ACCESS_TOKEN }}" \
            --header "Content-Type: application/json"
          )
          sleep 15
        done

        if [[ $attempt -ge 40 ]]; then
          echo "::error::Timeout waiting for repository creation. Aborting delivery process. Please contact someone from the DevSecOps team."
          exit 1
        fi

    - name: Publish RPMs
      shell: bash
      env:
        JF_URL: https://packages.centreon.com
        JF_ACCESS_TOKEN: ${{ inputs.artifactory_token }}
      run: |
        set -eux

        FILES="*.rpm"

        if [ -z "${{ inputs.module_name }}" ]; then
          echo "::error::module name is required"
          exit 1
        fi

        if [ -z "${{ inputs.distrib }}" ]; then
          echo "::error::distrib is required"
          exit 1
        fi

        # DEBUG
        echo "[DEBUG] - Version: ${{ inputs.version }}"
        echo "[DEBUG] - Distrib: ${{ inputs.distrib }}"
        echo "[DEBUG] - module_name: ${{ inputs.module_name }}"
        echo "[DEBUG] - is_cloud: ${{ inputs.is_cloud }}"
        echo "[DEBUG] - release_type: ${{ inputs.release_type }}"
        echo "[DEBUG] - stability: ${{ inputs.stability }}"
        echo "[DEBUG] - delivery_type: ${{ inputs.delivery_type }}"

        # Make sure all required inputs are NOT empty
        if [[ -z "${{ inputs.module_name }}" || -z "${{ inputs.distrib }}" || -z ${{ inputs.stability }} || -z ${{ inputs.version }} || -z "${{ inputs.is_cloud }}" ]]; then
          echo "::error::some mandatory inputs are empty, please check the logs."
          exit 1
        fi

        if [[ "${{ inputs.delivery_type }}" != "feature" && "${{ inputs.stability }}" != "testing" && "${{ inputs.stability }}" != "unstable" ]]; then
          echo "::error::stability must be one of: testing, unstable (got '${{ inputs.stability }}')"
          exit 1
        fi

        # Create ARCH dirs
        mkdir noarch x86_64

        # Get ARCH target for files to deliver and regroupe them by ARCH
        for FILE in $FILES; do
          echo "[DEBUG] - File: $FILE"

          ARCH=$(echo $FILE | grep -oP '(x86_64|noarch)')

          echo "[DEBUG] - Arch: $ARCH"

          mv "$FILE" "$ARCH"
        done

        if [[ "${{ inputs.delivery_type }}" == "feature" ]]; then
          ROOT_REPO_PATH="rpm-standard-feature-$(echo "${{ github.head_ref || github.ref_name }}" | grep -oP '^.*MON-[0-9]+')"
        elif [[ "${{ inputs.is_cloud }}" == "true" ]]; then
          ROOT_REPO_PATH="rpm-standard-internal"
        else
          ROOT_REPO_PATH="rpm-standard"
        fi

        for ARCH in "noarch" "x86_64"; do
          if [[ "${{ inputs.release_type }}" == "hotfix" || "${{ inputs.release_type }}" == "release" ]]; then
            UPLOAD_REPO_PATH="${{ inputs.version }}/${{ inputs.distrib }}/${{ inputs.stability }}-${{ inputs.release_type }}/$ARCH/${{ inputs.module_name }}/"
            REINDEX_STABILITY="${{ inputs.stability }}-${{ inputs.release_type }}"
          else
            UPLOAD_REPO_PATH="${{ inputs.version }}/${{ inputs.distrib }}/${{ inputs.stability }}/$ARCH/${{ inputs.module_name }}/"
            REINDEX_STABILITY="${{ inputs.stability }}"
          fi
          if [ "$(ls -A $ARCH)" ]; then
            jf rt upload "$ARCH/*.rpm" "$ROOT_REPO_PATH/$UPLOAD_REPO_PATH" --sync-deletes="$ROOT_REPO_PATH/$UPLOAD_REPO_PATH" --flat  --detailed-summary
          fi

          curl -H "Authorization: Bearer ${{ env.JF_ACCESS_TOKEN }}" -X POST "${{ env.JF_URL }}/artifactory/api/yum/$ROOT_REPO_PATH?path=/${{ inputs.version }}/${{ inputs.distrib }}/${REINDEX_STABILITY}/$ARCH&async=1"
        done
