# Its role is to performe the same checks that would be performed when publishing to galaxy
# Running them earlier helps to detect issues locally

name: galaxy-importer

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

on:
  pull_request:
    branches:
      - main

permissions: read-all

jobs:
  galaxy-importer:
    runs-on:
      - ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7

      - name: Set up Python
        uses: actions/setup-python@39cd14951b08e74b54015e9e001cdefcf80e669f # v5.1.1
        with:
          python-version: '3.10'

      - name: Get collection namespace and name from galaxy.yml
        id: collection-name
        run: |
          NAMESPACE=$(grep '^namespace:' galaxy.yml | awk '{print $2}' | tr -d "'\"")
          NAME=$(grep '^name:' galaxy.yml | awk '{print $2}' | tr -d "'\"")
          VERSION=$(grep '^version:' galaxy.yml | awk '{print $2}' | tr -d "'\"")
          if [[ -z "$NAMESPACE" || -z "$NAME" || -z "$VERSION" ]]; then
            echo "Error: Unable to find or parse namespace, name, or version in galaxy.yml"
            exit 1
          fi
          echo "Collection namespace is $NAMESPACE"
          echo "Collection name is $NAME"
          echo "Collection version is $VERSION"
          echo "COLLECTION_NAMESPACE=$NAMESPACE" >> $GITHUB_ENV
          echo "COLLECTION_NAME=$NAME" >> $GITHUB_ENV
          echo "COLLECTION_VERSION=$VERSION" >> $GITHUB_ENV

      - name: Install Ansible and importer
        run: |
          pip install ansible==9.4.0
          pip install ansible-importer
          pip install galaxy-importer

      - name: Build and install the collection
        run: |
          ansible-galaxy collection build $GITHUB_WORKSPACE --force
          ansible-galaxy collection install $GITHUB_WORKSPACE/$COLLECTION_NAMESPACE-$COLLECTION_NAME-$COLLECTION_VERSION.tar.gz

      - name: Run ac-galaxy-importer
        run: |
          python -m galaxy_importer.main $GITHUB_WORKSPACE/$COLLECTION_NAMESPACE-$COLLECTION_NAME-$COLLECTION_VERSION.tar.gz