name: Scheduled Fake Commits

on:
  # Trigger the workflow on a schedule.
  schedule:
    # This expression means "run every 3 minutes". Useful for testing.
    # To revert to the original 8-hour schedule, change this to '0 */8 * * *'.
    - cron: "0 */3 * * *" # Original schedule: every 8 hours

  # To trigger manually for testing, you can add workflow_dispatch:
  # workflow_dispatch:

jobs:
  create_scheduled_commits:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          # Fetch the full history to ensure pushes work correctly
          fetch-depth: 0
          # Use a token with write access. This should be stored as a secret in your Gitea repo settings.
          # The default GITEA_TOKEN might not have push permissions, so a Personal Access Token is recommended.
          # Ensure you have a secret named GITEA_TOKEN with appropriate permissions (including write:actions or api)
          token: ${{ secrets.GLOBAL_KEY }} # Replace GITEA_TOKEN with the name of your secret

      - name: Set up Git config
        # Configure Git user details globally for the runner
        run: |
          echo "setting up git config"
          git config --global user.name "Gitea Actions Bot"
          git config --global user.email "actions-bot@your-gitea-instance.com" # Replace with a suitable email
          echo "git config setup complete"

      - name: Create and Push Commits and Trigger Workflows
        id: push_commits_and_trigger # Updated ID
        env:
          # Define your list of authors here. Each author should be on a new line,
          # formatted as "Author Name <author@email.com>".
          # For production, this should ideally be stored as a secret named FAKE_COMMIT_AUTHORS.
          # For debugging, you can define it directly here as you have done.
          AUTHOR_LIST: |
            Author One <author1@example.com>
            Author Two <author2@example.com>
            Author Three <author3@example.com>
            Author Four <author4@example.com>
            Author Five <author5@example.com>
            Author Six <author6@example.com>
            Author Seven <author7@example.com>
            Author Eight <author8@example.com>
            Author Nine <author9@example.com>
            Author Ten <author10@example.com>
            DWSAuthor One <dwsauthor1@example.com>
            DWSAuthor Two <dwsauthor2@example.com>
            DWSAuthor Three <dwsauthor3@example.com>
            DWSAuthor Four <autdwshor4@example.com>
            DWSAuthor Five <autdwshor5@example.com>
            DWSAuthor Six <autdwshor6@example.com>
            DWSAuthor Seven <adwsuthor7@example.com>
            DWSAuthor Eight <adwsuthor8@example.com>
            DWSAuthor Nine <autdwshor9@example.com>
            DWSAuthor Ten <autdwshor10@example.com>
          COMMIT_COUNT: 12 # Number of commits to create
          SLEEP_SECONDS: 150 # Delay between commits in seconds
          TARGET_BRANCH: main # The branch to commit to and trigger workflows on
          GITEA_BASE_URL: https://git.dws.rip # Replace with your Gitea instance URL
          REPO_OWNER: dubey # Replace with your repository owner/organization
          REPO_NAME: WebGoat # Replace with your repository name
          # Define a space-separated list of workflow names to trigger
          WORKFLOW_NAMES: "DDSAST DDSDS DDSCA" # Replace with the actual names of your workflows

        run: |
          echo "starting Create and Push Commits and Trigger Workflows step"
          echo "AUTHOR_LIST content:"
          # Mask sensitive content if AUTHOR_LIST were a secret, but here it's in the workflow file for debugging
          # echo "$AUTHOR_LIST" | sed 's/@[^>]*>/@***/g' # Example masking

          echo "reading author's list into array"
          # Read authors into a Bash array using readarray
          readarray -t authors <<< "$AUTHOR_LIST"
          echo "finished reading author's list into array"

          # Check if authors list is empty
          if [ ${#authors[@]} -eq 0 ]; then
            echo "Error: AUTHOR_LIST is empty or could not be parsed into an array."
            exit 1
          fi

          # Shuffle the authors array to randomize the order
          authors=($(printf "%s\n" "${authors[@]}" | shuf))

          # Read workflow names into a Bash array
          IFS=' ' read -r -a workflow_array <<< "$WORKFLOW_NAMES"
          echo "Workflows to trigger: ${workflow_array[@]}"

          echo "Starting commit creation process..."
          echo "Authors available: ${#authors[@]}"
          echo "Commits to create: $COMMIT_COUNT"
          echo "Delay between commits: $SLEEP_SECONDS seconds"
          echo "Target branch: $TARGET_BRANCH"

          # Loop to create the specified number of commits
          for i in $(seq 1 $COMMIT_COUNT); do
            # Calculate the index for the current author, cycling through the list
            author_index=$(( (i - 1) % ${#authors[@]} ))
            current_author="${authors[$author_index]}"

            echo "Processing author: $current_author" # Debug echo

            # Extract name and email from the author string
            # Assumes format "Name <email>"
            author_name=$(echo "$current_author" | sed -E 's/^(.*) <.*>$/\1/')
            author_email=$(echo "$current_author" | sed -E 's/^.* <(.*)>$/\1/')

            echo "Extracted name: $author_name, email: $author_email" # Debug echo

            echo "--- Creating commit $i of $COMMIT_COUNT by $author_name ---"

            # Configure git user for this specific commit
            git config user.name "$author_name"
            git config user.email "$author_email"

            # Create a dummy change: append current timestamp and author to a file
            # This ensures there's always something to commit
            echo "$(date): Commit $i by $author_name" >> fake_commit_log.txt

            # Stage the changes
            git add fake_commit_log.txt

            # Commit the changes
            git commit -m "Automated commit $i by $author_name"

            # Push the commit to the target branch
            # Use --set-upstream origin $TARGET_BRANCH on the first push if needed
            echo "Pushing commit..."
            git push origin HEAD:$TARGET_BRANCH

            echo "Commit $i pushed successfully."

            # --- Trigger the other workflows after each successful push ---
            echo "Triggering specified workflows on branch '$TARGET_BRANCH' for commit $i..."

            # Loop through the list of workflow names and trigger each one
            for workflow_name in "${workflow_array[@]}"; do
              echo "Attempting to trigger workflow: $workflow_name"
              # Construct the API URL
              API_URL="${GITEA_BASE_URL}/api/v1/repos/${REPO_OWNER}/${REPO_NAME}/actions/workflows/${workflow_name}/dispatches"

              # Use curl to send the API request
              # Requires a GITEA_TOKEN with write:actions or api scope
              curl -X POST \
                -H "Authorization: Bearer ${{ secrets.GLOBAL_KEY }}" \
                -H "Content-Type: application/json" \
                -d '{"ref": "'"$TARGET_BRANCH"'"}' \
                "$API_URL"

              echo "Workflow trigger request sent for workflow '$workflow_name' for commit $i."
            done
            echo "Finished triggering workflows for commit $i."
            # --- End Trigger ---


            # Wait for the specified delay before the next commit, unless it's the last one
            if [ $i -lt $COMMIT_COUNT ]; then
              echo "Waiting for $SLEEP_SECONDS seconds before the next commit..."
              sleep $SLEEP_SECONDS
            fi
          done

          echo "Finished creating $COMMIT_COUNT commits and triggering workflows."