name: Update JSON Date on PR
on:
  pull_request:
    branches:
      - main
    types:
      - opened
      - synchronize
      - reopened

jobs:
  update-json-date:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout PR Branch
      uses: actions/checkout@v4
      with:
        ref: ${{ github.head_ref }}
        token: ${{ secrets.JSON_APP_KEY }}
    - name: Update Date in JSON-Files 
      run: |
        BASE_BRANCH=${{ github.event.pull_request.base.ref }}
        HEAD_BRANCH=${{ github.event.pull_request.head.ref }}
        
        git fetch origin $BASE_BRANCH       
        
        CHANGED_FILES=$(git diff --name-only origin/$BASE_BRANCH HEAD)
        
        echo "Changed files: $CHANGED_FILES"
               
        for FILE in $CHANGED_FILES; do
          if [[ "$FILE" =~ /(.*)\.sh ]]; then
            echo ${BASH_REMATCH[1]}
            NAME="$(echo "${BASH_REMATCH[1]}" | sed 's/-install//')"
          elif [[ "$FILE" =~ /(.*)\.json ]]; then
            NAME="${BASH_REMATCH[1]}"
          else
            echo "no Match on $FILE"
            continue
          fi
          
          JSON_FILE="json/${NAME}.json"
          if [[ -f "$JSON_FILE" ]]; then
            echo "Updating date_created in $JSON_FILE"
            jq --arg date "$(date +%Y-%m-%d)" '.date_created = $date' "$JSON_FILE" > tmp.json && mv tmp.json "$JSON_FILE"
          else
            echo "JSON file $JSON_FILE not found"
          fi
        done
             
        git config --global user.name "json-updater-bot[bot]"
        git config --global user.email "json-updater-bot[bot]@users.noreply.github.com"
        git diff --exit-code || git commit -am "Updating Dates in affected JSON files."
        git push 
      env:
        GH_TOKEN: ${{ secrets.JSON_APP_KEY }}
        APP_ID: ${{ secrets.JSON_APP_ID }}