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 and Extract Script Type
        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,body)
          filtered_issue=$(echo "$raw_output" | jq -r '[.[] | select(.labels[]?.name == "Migration To ProxmoxVE")][0]')

          if [ "$filtered_issue" == "null" ] || [ -z "$filtered_issue" ]; then
            echo "No issues found with label 'Migration To ProxmoxVE'."
            exit 1
          fi

          script_name=$(echo "$filtered_issue" | jq -r '.title' | tr '[:upper:]' '[:lower:]' | tr -d ' ')
          issue_nr=$(echo "$filtered_issue" | jq -r '.number')
          issue_body=$(echo "$filtered_issue" | jq -r '.body')

          echo "Script Name: $script_name"
          echo "Issue Number: $issue_nr"

          # Detect script type from issue body
          if echo "$issue_body" | grep -qi "CT (LXC Container)"; then
            script_type="ct"
          elif echo "$issue_body" | grep -qi "VM (Virtual Machine)"; then
            script_type="vm"
          elif echo "$issue_body" | grep -qi "Addon (tools/addon)"; then
            script_type="addon"
          elif echo "$issue_body" | grep -qi "PVE Tool (tools/pve)"; then
            script_type="pve"
          else
            # Fallback detection by filename pattern
            if [[ "$script_name" == *"-vm"* ]]; then
              script_type="vm"
            else
              script_type="ct"
            fi
          fi

          echo "Script Type: $script_type"

          echo "script_name=$script_name" >> $GITHUB_OUTPUT
          echo "issue_nr=$issue_nr" >> $GITHUB_OUTPUT
          echo "script_type=$script_type" >> $GITHUB_OUTPUT

      - name: Check if script files exist
        id: check_files
        run: |
          script_name="${{ steps.list_issues.outputs.script_name }}"
          script_type="${{ steps.list_issues.outputs.script_type }}"
          files_found="true"
          missing_files=""

          # Check files based on script type
          case "$script_type" in
            ct)
              if [[ ! -f "ct/${script_name}.sh" ]]; then
                echo "ct file not found: ct/${script_name}.sh"
                files_found="false"
                missing_files+="ct/${script_name}.sh "
              fi
              if [[ ! -f "install/${script_name}-install.sh" ]]; then
                echo "install file not found: install/${script_name}-install.sh"
                files_found="false"
                missing_files+="install/${script_name}-install.sh "
              fi
              # JSON check with alpine fallback
              json_file="frontend/public/json/${script_name}.json"
              if [[ ! -f "$json_file" ]]; then
                if [[ "$script_name" == alpine-* ]]; then
                  stripped_name="${script_name#alpine-}"
                  alt_json="frontend/public/json/${stripped_name}.json"
                  if [[ -f "$alt_json" ]]; then
                    echo "Using alpine fallback JSON: $alt_json"
                    echo "json_fallback=$alt_json" >> $GITHUB_OUTPUT
                  else
                    echo "json file not found: $json_file"
                    files_found="false"
                    missing_files+="$json_file "
                  fi
                else
                  echo "json file not found: $json_file"
                  files_found="false"
                  missing_files+="$json_file "
                fi
              fi
              ;;
            vm)
              if [[ ! -f "vm/${script_name}.sh" ]]; then
                echo "vm file not found: vm/${script_name}.sh"
                files_found="false"
                missing_files+="vm/${script_name}.sh "
              fi
              # JSON is optional for VMs but check anyway
              json_file="frontend/public/json/${script_name}.json"
              if [[ ! -f "$json_file" ]]; then
                echo "json file not found (optional): $json_file"
              fi
              ;;
            addon)
              if [[ ! -f "tools/addon/${script_name}.sh" ]]; then
                echo "addon file not found: tools/addon/${script_name}.sh"
                files_found="false"
                missing_files+="tools/addon/${script_name}.sh "
              fi
              # JSON is optional for addons
              json_file="frontend/public/json/${script_name}.json"
              if [[ ! -f "$json_file" ]]; then
                echo "json file not found (optional): $json_file"
              fi
              ;;
            pve)
              if [[ ! -f "tools/pve/${script_name}.sh" ]]; then
                echo "pve tool file not found: tools/pve/${script_name}.sh"
                files_found="false"
                missing_files+="tools/pve/${script_name}.sh "
              fi
              ;;
          esac

          echo "files_found=$files_found" >> $GITHUB_OUTPUT
          echo "missing=$missing_files" >> $GITHUB_OUTPUT

      - 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 }}"
          script_type="${{ steps.list_issues.outputs.script_type }}"
          gh issue comment ${{ steps.list_issues.outputs.issue_nr }} --body "Not all required files were found for **$script_name** (type: $script_type). 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 }}"
          timestamp=$(date +%s)
          branch_name="add-script-${script_name//[^a-zA-Z0-9_-]/}-${timestamp}"
          echo "Using branch: $branch_name"
          echo "branch_name=$branch_name" >> $GITHUB_ENV

      - name: Clone ProxmoxVE and Copy Files
        run: |
          script_name="${{ steps.list_issues.outputs.script_name }}"
          script_type="${{ steps.list_issues.outputs.script_type }}"
          json_fallback="${{ steps.check_files.outputs.json_fallback }}"

          git clone https://x-access-token:${{ steps.app-token.outputs.token }}@github.com/community-scripts/ProxmoxVE.git ProxmoxVE
          cd ProxmoxVE

          # Check if branch already exists remotely and delete it
          if git ls-remote --exit-code --heads origin "$branch_name" >/dev/null 2>&1; then
            echo "Branch $branch_name already exists remotely, deleting it..."
            git push origin --delete "$branch_name" || true
          fi

          # Check if files already exist in target repo
          case "$script_type" in
            ct)
              [[ -f "ct/${script_name}.sh" ]] && echo "ct file already exists in ProxmoxVE" && exit 1
              [[ -f "install/${script_name}-install.sh" ]] && echo "install file already exists in ProxmoxVE" && exit 1
              ;;
            vm)
              [[ -f "vm/${script_name}.sh" ]] && echo "vm file already exists in ProxmoxVE" && exit 1
              ;;
            addon)
              [[ -f "tools/addon/${script_name}.sh" ]] && echo "addon file already exists in ProxmoxVE" && exit 1
              ;;
            pve)
              [[ -f "tools/pve/${script_name}.sh" ]] && echo "pve tool file already exists in ProxmoxVE" && exit 1
              ;;
          esac

          git checkout -b "$branch_name"

          # Copy files based on script type
          case "$script_type" in
            ct)
              cp ../ct/${script_name}.sh ct/
              cp ../ct/headers/${script_name} ct/headers/ 2>/dev/null || true
              cp ../install/${script_name}-install.sh install/

              # Handle JSON with alpine fallback
              if [[ -n "$json_fallback" ]]; then
                cp ../${json_fallback} frontend/public/json/ || true
              else
                cp ../frontend/public/json/${script_name}.json frontend/public/json/ 2>/dev/null || true
              fi

              # Update URLs in ct script
              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|community-scripts/ProxmoxVED|community-scripts/ProxmoxVE|g" ct/${script_name}.sh
              sed -i "s|community-scripts/ProxmoxVED|community-scripts/ProxmoxVE|g" install/${script_name}-install.sh
              ;;
            vm)
              cp ../vm/${script_name}.sh vm/
              cp ../frontend/public/json/${script_name}.json frontend/public/json/ 2>/dev/null || true

              # Update URLs in vm script
              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|" vm/${script_name}.sh
              sed -i "s|community-scripts/ProxmoxVED|community-scripts/ProxmoxVE|g" vm/${script_name}.sh
              ;;
            addon)
              mkdir -p tools/addon
              cp ../tools/addon/${script_name}.sh tools/addon/
              cp ../frontend/public/json/${script_name}.json frontend/public/json/ 2>/dev/null || true

              # Update URLs in addon script
              sed -i "s|community-scripts/ProxmoxVED|community-scripts/ProxmoxVE|g" tools/addon/${script_name}.sh
              ;;
            pve)
              mkdir -p tools/pve
              cp ../tools/pve/${script_name}.sh tools/pve/

              # Update URLs in pve script
              sed -i "s|community-scripts/ProxmoxVED|community-scripts/ProxmoxVE|g" tools/pve/${script_name}.sh
              ;;
          esac

          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 "Add ${script_name} (${script_type})"

      - 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 }}"
          script_type="${{ steps.list_issues.outputs.script_type }}"
          gh pr create \
            --repo community-scripts/ProxmoxVE \
            --head "$branch_name" \
            --base main \
            --title "${script_name}" \
            --body "Automated migration of **${script_name}** (type: ${script_type}) 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"
