name: Check Shell Scripts

on:
  pull_request:
    paths:
      - '**/*.sh'  # Führt den Check nur für Shell-Skripte aus

jobs:
  check-scripts:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout Code
      uses: actions/checkout@v3

    - name: Check `source` Line in Scripts
      shell: bash
      run: |
        set -e
        ERROR_COUNT=0
        FILES=$(find . -name "*.sh")

        for FILE in $FILES; do
          # Check for exact match of the source line in line 2
          if [[ $(sed -n '2p' "$FILE") =~ ^source[[:space:]]+<(curl -s https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func) ]]; then
            echo "Check passed for: $FILE"
          else
            echo "Error in $FILE: Line 2 must be exactly 'source <(curl -s https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func)' if a source line is used."
            ERROR_COUNT=$((ERROR_COUNT + 1))
          fi

          # Check for shebang line at the top
          if [[ $(head -n 1 "$FILE") != "#!/usr/bin/env bash" ]]; then
            echo "Error in $FILE: The first line must be '#!/usr/bin/env bash'."
            ERROR_COUNT=$((ERROR_COUNT + 1))
          fi

          # Check for executable permissions
          if [[ ! -x "$FILE" ]]; then
            echo "Warning in $FILE: This script is not executable. Consider running 'chmod +x $FILE'."
          fi

          # Check for empty lines at the beginning of the script
          if [[ $(head -n 10 "$FILE" | grep -c '^$') -gt 0 ]]; then
            echo "Warning in $FILE: There are empty lines at the beginning of the script. Consider removing them."
          fi
        done

        if [[ "$ERROR_COUNT" -gt 0 ]]; then
          echo "$ERROR_COUNT script(s) failed validation."
          exit 1
        else
          echo "All scripts passed."
        fi