#!/usr/bin/env bash

curl --request GET \
  --header "PRIVATE-TOKEN: $SELF_GITLAB_TOKEN" \
  "https://gitlab.ellisbs.co.uk/api/v4/projects" 2>/dev/null |
  jq -r '.[] | select(.id) | "\(.id) \(.name)"' |
  while read -r project_id project_name; do
    # Get the schedule ID for the "daily" schedule in this project
    schedule_id=$(curl --request GET \
      --header "PRIVATE-TOKEN: $SELF_GITLAB_TOKEN" \
      "https://gitlab.ellisbs.co.uk/api/v4/projects/${project_id}/pipeline_schedules" 2>/dev/null |
      jq -r '.[] | select(.description=="Build packages") | .id')

    echo "Project_name: $project_name Project_id: $project_id Schedule_id: $schedule_id"
    if [ -n "$schedule_id" ]; then
      echo "Triggering schedule for $project_name (ID: $project_id)"
      # Trigger the pipeline schedule
      curl --request POST \
        --header "PRIVATE-TOKEN: $SELF_GITLAB_TOKEN" \
        "https://gitlab.ellisbs.co.uk/api/v4/projects/${project_id}/pipeline_schedules/${schedule_id}/play"
    fi
  done
