#!/bin/bash
# Email Organizer Control — enable/disable all email organizer cron jobs
#
# Usage:
#   gmail-organizer-ctl.sh stop    — disable all cron jobs (frees LLM)
#   gmail-organizer-ctl.sh start   — re-enable all cron jobs
#   gmail-organizer-ctl.sh status  — show current state

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CRON_MARKER_1="gmail-organizer/gmail_organizer.py"
CRON_MARKER_2="gmail-organizer-dvish/gmail_organizer.py"
CRON_MARKER_3="proton-organizer/proton_organizer.py"

case "${1:-status}" in
  stop|disable|pause)
    crontab -l 2>/dev/null | sed \
      -e "/${CRON_MARKER_1//\//\\/}/s/^/#PAUSED# /" \
      -e "/${CRON_MARKER_2//\//\\/}/s/^/#PAUSED# /" \
      -e "/${CRON_MARKER_3//\//\\/}/s/^/#PAUSED# /" \
      | crontab -
    echo "Email organizers PAUSED (all 3 accounts)"
    echo "LLM is free. Run '$0 start' to resume."
    ;;
  start|enable|resume)
    crontab -l 2>/dev/null | sed \
      -e "s/^#PAUSED# \(.*${CRON_MARKER_1//\//\\/}\)/\1/" \
      -e "s/^#PAUSED# \(.*${CRON_MARKER_2//\//\\/}\)/\1/" \
      -e "s/^#PAUSED# \(.*${CRON_MARKER_3//\//\\/}\)/\1/" \
      | crontab -
    echo "Email organizers RESUMED (all 3 accounts)"
    ;;
  status)
    echo "Email Organizer Status:"
    crontab -l 2>/dev/null | grep -E "gmail-organizer|proton-organizer" | while read -r line; do
      if echo "$line" | grep -q "^#PAUSED#"; then
        echo "  PAUSED: $(echo "$line" | sed 's/#PAUSED# //')"
      else
        echo "  ACTIVE: $line"
      fi
    done
    ;;
  *)
    echo "Usage: $0 {stop|start|status}"
    exit 1
    ;;
esac
