name: KiBot CI
on:
  workflow_dispatch:
  push:
    tags:
      - release/rev-**
    branches:
      - main
      - dev
      - review/rev-**
    paths-ignore:
      - '*.md'

env:
  # KiBot Configuration
  kibot_cache: kibot/cache
  kibot_config: kibot/yaml/kibot_main.yaml
  kibot_draft: true
  kibot_log: kibot_run.log

  # Update these to correspond to the KiCad version
  kibot_group: "all_group"
  kibot_tag: "dev"

jobs:
  test:
    runs-on: ubuntu-latest
    container: ghcr.io/inti-cmnb/kicad9_auto_full:${{ env.kibot_tag }}
    if: ${{ github.ref_type == 'tag' || !startsWith(github.event.head_commit.message, 'Merge pull request') }}

    steps:
      - name: Install NodeJS
        run: |
          apt-get update && apt -y install --no-install-recommends nodejs

      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          sparse-checkout: null

      - name: Determine Release Stage
        shell: bash
        run: |
          stage=unknown
          if [ "${{ github.ref == 'refs/heads/dev' }}" = "true" ] ; then
            if [ "${{ env.kibot_draft }}" = "true" ] ; then
              stage=DRAFT
            else
              stage=WORKING
            fi
          else
            if [ "${{ env.kibot_draft}}" == "true" ] ; then
              echo "Error: kibot_draft is set outside of dev branch"
              exit 1
            fi

            if [ "${{ startsWith(github.ref, 'refs/heads/review/rev-') }}" = "true" ] ; then
              stage=REVIEW
            elif [ "${{ github.ref_type == 'tag' }}" = "true" ] ; then
              stage=RELEASE
            else
              echo "Error: could not determine release stage"
              exit 1
            fi
          fi

          echo "Release Stage: $stage"
          echo "kibot_stage=$stage" > $GITHUB_ENV

      - name: Setup KiBot Arguments
        shell: bash
        run: |
          last_tag=$(git describe --tags --abbrev=0 || echo "NO_TAG")
          echo "Last tag: ${last_tag}"
          if [ "${{ github.ref_type }}" = "tag" ]; then
            version_arg="-E RELEASE_STATE='RELEASE' -E REVISION='${last_tag##release/rev-}'"
            echo "Overriding kibot_variant to 'RELEASE' for tag"
            echo "kibot_variant=RELEASE" >> $GITHUB_ENV
          else
            version_arg="-E RELEASE_STATE='${{ env.kibot_stage }}' -E REVISION='${last_tag##release/rev-}+ (Unreleased)'"
            echo "kibot_variant=${{ env.kibot_stage }}" >> $GITHUB_ENV
          fi

          case "$kibot_stage" in
            "DRAFT")
              additional_args="--skip-pre draw_fancy_stackup,erc,drc ${version_arg} --log ${{ env.kibot_log }} draft_group"
              ;;
            "WORKING")
              additional_args="--skip-pre erc,drc ${version_arg} -E BLENDER_SAMPLES=2 --log ${{ env.kibot_log }} ${{ env.kibot_group }}"
              ;;
            "REVIEW"|"RELEASE")
              additional_args="${version_arg} --log ${{ env.kibot_log }} ${{ env.kibot_group }}"
              ;;
            *)
              echo "Unknown Stage: $kibot_stage"
              exit 1
              ;;
          esac

          echo "version_arg=${version_arg}" >> $GITHUB_ENV
          echo "additional_args=${additional_args}" >> $GITHUB_ENV

      - name: Remove KiRi Files from Prior Revisions
        shell: bash
        run: '[ -d kiri ] && git rm -rf kiri/* || echo "No KiRi files to delete"'

      - name: Retrieve Cached 3d Models
        id: cache-models-restore
        uses: actions/cache/restore@v4
        with:
          path: ${{ env.kibot_cache }}/3d_models
          key: 3d_models

      - name: Check KiBot Version Information
        shell: bash
        run: |
          kibot --version | awk '{ print $1 ": "  $2 }'
          echo KiCad: `dpkg --robot -l kicad | grep kicad | awk '{print $3}'`
          echo Debian: `cat /etc/debian_version`
          pcbnew_do --version  | awk 'BEGIN{ done=0 } { if (done == 0) { print "KiAuto: " $2; done=1 } }'
          echo "iBoM:" `INTERACTIVE_HTML_BOM_NO_DISPLAY=True generate_interactive_bom.py --version 2> /dev/null | grep "^v" | tr -d 'v'`

      - name: Run KiBot (Update XML)
        shell: bash
        run: |
          /usr/bin/kicad-git-filters.py
          kibot -c kibot/yaml/kibot_pre_update_xml.yaml -d . --log kibot_run_xml.log

      - name: Run KiBot (Preprocessing)
        shell: bash
        run: |
          /usr/bin/kicad-git-filters.py
          kibot -c ${{ env.kibot_config }} \
                -d . \
                --log kibot_run_preprocess.log \
                --skip-pre all \
                ${{ env.version_arg }} \
                preprocess_group

      - name: Run KiBot (Outputs)
        shell: bash
        run: |
          /usr/bin/kicad-git-filters.py
          export KIBOT_3D_MODELS="${{ env.kibot_cache }}/3d_models"
          echo Exporting KIBOT_3D_MODELS=$KIBOT_3D_MODELS
          kibot -c ${{ env.kibot_config }} -d . ${{ env.additional_args }}

      - name: Save Cached 3d Models
        id: cache-models-save
        if: always()
        uses: actions/cache/save@v4
        with:
          path: ${{ env.kibot_cache }}/3d_models
          key: ${{ steps.cache-models-restore.outputs.cache-primary-key }}

      - name: Pull latest changes
        shell: bash
        run: |
          git config --global user.email "gitea-actions[bot]@users.noreply.git.asymworks.com"
          git config --global user.name "Gitea Actions"

          if [ "${{ github.ref_type }}" = "tag" ]; then
            echo "Triggered by a tag, committing changes in detached HEAD state"
            git add -A
            git commit -m "[bot]: Update Outputs (release)"

            DETACHED_COMMIT=$(git rev-parse HEAD)
            echo "Checking out the main branch"
            git fetch origin main
            git checkout main

            echo "Merging detached HEAD commit into main"
            git merge --no-ff $DETACHED_COMMIT -m "[bot]: Merge release artifacts from workflow" -X theirs
            echo "Pushing to main branch"
            git push origin main
          else
            echo "Triggered by a branch, using the current branch"
            git pull origin ${{ github.ref_name }} --tags --force
          fi

      - name: Discard changes to .kicad_pcb files and remove temp files
        run: | 
          git checkout HEAD -- $(git ls-files "*.kicad_pcb")
          git clean -f -e "panels/*" "*.kicad_pcb"
          git clean -f -e "panels/*" "*.kicad_pro"
          git clean -f -e "panels/*" "*.kicad_dru"
          git clean -f -e "panels/*" "*.kicad_prl"

      - name: Push Outputs
        uses: stefanzweifel/git-auto-commit-action@v5
        with:
          branch: ${{ github.ref_name }}
          commit_message: '[bot]: Update Outputs'

      - name: Upload XML Update Log
        if: ${{ always() }} 
        uses: christopherhx/gitea-upload-artifact@v4
        with:
          name: log_file_xml
          path: kibot_run_xml.log

      - name: Upload Preprocessing Log
        if: ${{ always() }} 
        uses: christopherhx/gitea-upload-artifact@v4
        with:
          name: log_file_preprocess
          path: kibot_run_preprocess.log

      - name: Upload KiBot Log
        if: ${{ always() }}
        uses: christopherhx/gitea-upload-artifact@v4
        with:
          name: log_file_kibot
          path: ${{ env.kibot_log }}
