name: Move new Scripts to Main Repository

on:
  workflow_dispatch:
  issues:
    types:
      - labeled

permissions:
  contents: write
  issues: write
  pull-requests: write

jobs:
  move-to-main-repo:
    runs-on: ubuntu-latest
    if: github.event.label.name == 'Migration To ProxmoxVE' && github.repository == 'community-scripts/ProxmoxVED'
    steps:
      - name: Generate a token
        id: app-token
        uses: actions/create-github-app-token@v2
        with:
          app-id: ${{ vars.PUSH_MAIN_APP_ID }}
          private-key: ${{ secrets.PUSH_MAIN_APP_SECRET }}
          owner: community-scripts
          repositories: |
            ProxmoxVE
            ProxmoxVED

      - name: Checkout ProxmoxVED (Source Repo)
        uses: actions/checkout@v4
        with:
          ref: main
          repository: community-scripts/ProxmoxVED
          token: ${{ secrets.GH_MERGE_PAT }}

      - name: List Issues in Repository
        id: list_issues
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          echo "Filtering Issues with Label Migration To ProxmoxVE"
          raw_output=$(gh issue list --json title,labels,number)
          filtered_issues=$(echo "$raw_output" | jq -r '.[] | select(.labels[]?.name == "Migration To ProxmoxVE") | .title' | head -n 1)
          issue_nr=$(echo "$raw_output" | jq -r '.[] | select(.labels[]?.name == "Migration To ProxmoxVE") | .number' | head -n 1)

          if [ -z "$filtered_issues" ]; then
            echo "No issues found with label 'Migration To ProxmoxVE'."
            exit 1
          else
            script_name=$(echo "$filtered_issues" | head -n 1) # Nur das erste Issue nehmen
            script_name_lowercase=$(echo "$script_name" | tr '[:upper:]' '[:lower:]' | tr -d ' ')
            echo "Script Name: $script_name_lowercase"
            echo "script_name=$script_name_lowercase" >> $GITHUB_OUTPUT
            echo "issue_nr=$issue_nr" >> $GITHUB_OUTPUT
          fi

      - name: Check if script files exist
        id: check_files
        run: |
          script_name="${{ steps.list_issues.outputs.script_name }}"
          ct_file="ct/${script_name}.sh"
          install_file="install/${script_name}-install.sh"
          json_file="frontend/public/json/${script_name}.json"


          if [[ ! -f "$ct_file" ]]; then
             echo "ct file not found."
             echo "files_found=false" >> $GITHUB_OUTPUT
             echo "missing=$ct_file" >> $GITHUB_OUTPUT
          fi
          if [[ ! -f "$install_file" ]]; then
             echo "install file not found."
             echo "files_found=false" >> $GITHUB_OUTPUT
             echo "missing=$install_file" >> $GITHUB_OUTPUT
          fi
          if [[ ! -f "$json_file" ]]; then
            if [[ "$json_file" = *alpine* ]]; then
              stripped_name="${json_file/frontend\/public\/json\/alpine-/frontend/public/json/}"
              echo $stripped_name
              if [[ -f "$stripped_name" ]]; then
                echo "files_found=true" >> $GITHUB_OUTPUT
              else
                echo "json file striped not found."
                echo "files_found=false" >> $GITHUB_OUTPUT
                echo "missing=$json_file" >> $GITHUB_OUTPUT
              fi
            else
             echo "json file not found."
             echo "files_found=false" >> $GITHUB_OUTPUT
             echo "missing=$json_file" >> $GITHUB_OUTPUT
            fi
          fi

      - name: Comment if not all Files found
        if: steps.check_files.outputs.files_found == 'false'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          script_name="${{ steps.list_issues.outputs.script_name }}"
          gh issue comment ${{ steps.list_issues.outputs.issue_nr }} --body "Not all required files were found for $script_name. Please check the files and try again. Missing: ${{ steps.check_files.outputs.missing }}."
          exit 1

      - name: Get GitHub App User ID
        id: get-user-id
        run: echo "user-id=$(gh api "/users/${{ steps.app-token.outputs.app-slug }}[bot]" --jq .id)" >> "$GITHUB_OUTPUT"
        env:
          GH_TOKEN: ${{ steps.app-token.outputs.token }}

      - name: Configure Git User
        run: |
          git config --global user.name '${{ steps.app-token.outputs.app-slug }}[bot]'
          git config --global user.email '${{ steps.get-user-id.outputs.user-id }}+${{ steps.app-token.outputs.app-slug }}[bot]@users.noreply.github.com'

      - name: Prepare branch name
        run: |
          script_name="${{ steps.list_issues.outputs.script_name }}"
          branch_name="add-script-${script_name//[^a-zA-Z0-9_-]/}"
          echo "Using branch: $branch_name"
          echo "branch_name=$branch_name" >> $GITHUB_ENV

      - name: Clone ProxmoxVE (Target Repo)
        run: |
          script_name="${{ steps.list_issues.outputs.script_name }}"
          git clone https://x-access-token:${{ steps.app-token.outputs.token }}@github.com/community-scripts/ProxmoxVE.git ProxmoxVE
          cd ProxmoxVE

          if [[ -f "ct/${script_name}.sh" ]]; then
            echo "ct file already exists in ProxmoxVE"
            exit 1
          fi
          if [[ -f "install/${script_name}-install.sh" ]]; then
            echo "install file already exists in ProxmoxVE"
            exit 1
          fi

          git checkout -b "$branch_name"

          cp ../ct/$script_name.sh ct/.
          cp ../ct/headers/$script_name ct/headers/. || true
          cp ../install/$script_name-install.sh install/.

          json_file="${script_name}.json"

          if [[ ! -f "../frontend/public/json/$json_file" ]]; then
            if [[ "$json_file" = *alpine* ]]; then
              stripped_name="${json_file#alpine-}"
              if [[ -f "../frontend/public/json/$stripped_name" ]]; then
                cp ../frontend/public/json/$stripped_name frontend/public/json/. || true
              fi
            fi
          else
            cp ../frontend/public/json/$json_file frontend/public/json/. || true
          fi

          echo $script_name
          sed -i "s|https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main/misc/build.func|https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func|" ct/$script_name.sh
          sed -i "s|https://git.community-scripts.org/community-scripts/ProxmoxVED/raw/branch/main/misc/build.func|https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func|" ct/$script_name.sh
          sed -i "s|# License: MIT \| https://github.com/community-scripts/ProxmoxVED/raw/main/LICENSE|# License: MIT \| https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE|" ct/$script_name.sh
          sed -i "s|# License: MIT \| https://github.com/community-scripts/ProxmoxVED/raw/main/LICENSE|# License: MIT \| https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE|" install/$script_name-install.sh

          git add . > /dev/null 2>&1
          if git diff --cached --exit-code; then
            echo "No changes detected, skipping commit."
            exit 0
          fi

          git commit -m "${commit_message:-'Add new script'}"

      - name: Push to ProxmoxVE
        run: |
          cd ProxmoxVE
          git push --no-thin origin "$branch_name"

      - name: Create Pull Request in ProxmoxVE
        id: create_pull_request
        env:
          GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
        run: |
          script_name="${{ steps.list_issues.outputs.script_name }}"
          gh pr create \
            --repo community-scripts/ProxmoxVE \
            --head "$branch_name" \
            --base main \
            --title "$script_name" \
            --body "Automated migration of $script_name from ProxmoxVED to ProxmoxVE."
          PR_NUMBER=$(gh pr list --repo community-scripts/ProxmoxVE --head "$branch_name" --json number --jq '.[].number')
          echo "PR_NUMBER=$PR_NUMBER"
          echo "pr_number=$PR_NUMBER" >> $GITHUB_OUTPUT

      - name: Comment on Issue
        if: steps.create_pull_request.outputs.pr_number
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          gh issue comment ${{ steps.list_issues.outputs.issue_nr }} --body "A PR has been created for ${{ steps.list_issues.outputs.script_name }}: community-scripts/ProxmoxVE#${{ steps.create_pull_request.outputs.pr_number }}"
          gh issue edit ${{ steps.list_issues.outputs.issue_nr }} --remove-label "Migration To ProxmoxVE" --add-label "Started Migration To ProxmoxVE"
