# endless-dl-commands.sh: tmux helper commands for endless-download.py
#
# Install on the server:
#   cp endless-dl-commands.sh ~/.endless-dl-commands.sh
#   echo 'source ~/.endless-dl-commands.sh' >> ~/.bashrc
#   source ~/.bashrc
#
# Commands:
#   dl-start [args]   start in a detached tmux session (args pass through, e.g. dl-start -r 300 -n 4)
#   dl-status         print the current live readout without attaching
#   dl-attach         attach to the session (detach again with Ctrl+b then d)
#   dl-stop           stop the download, print the final summary, close the session

DL_SCRIPT="${DL_SCRIPT:-$HOME/endless-download.py}"
DL_SESSION="${DL_SESSION:-endless-dl}"

_dl_exists() { tmux has-session -t "$DL_SESSION" 2>/dev/null; }

# True if the script is still running inside the session's pane
_dl_running() {
  local pid
  pid=$(tmux display-message -p -t "$DL_SESSION" '#{pane_pid}' 2>/dev/null) || return 1
  pgrep -f -P "$pid" "endless-download.py" >/dev/null 2>&1
}

dl-start() {
  if [ ! -f "$DL_SCRIPT" ]; then
    echo "Script not found at $DL_SCRIPT (set DL_SCRIPT=/path/to/endless-download.py)"
    return 1
  fi
  if _dl_exists && _dl_running; then
    echo "Already running in tmux session '$DL_SESSION'. Use dl-status, dl-attach or dl-stop."
    return 0
  fi
  if ! _dl_exists; then
    tmux new-session -d -s "$DL_SESSION" -x 200 -y 50
  fi
  # Run via send-keys so the pane stays open if the script exits or errors
  tmux send-keys -t "$DL_SESSION" "clear; python3 $(printf '%q' "$DL_SCRIPT") $*" Enter
  echo "Started in tmux session '$DL_SESSION'."
  sleep 3
  dl-status
}

dl-status() {
  if ! _dl_exists; then
    echo "Not running (no tmux session '$DL_SESSION')."
    return 1
  fi
  _dl_running || echo "(session exists but the script isn't running, last output below)"
  tmux capture-pane -p -t "$DL_SESSION" | sed '/^[[:space:]]*$/d' | tail -n 10
}

dl-attach() {
  if ! _dl_exists; then
    echo "Not running. Start it with dl-start."
    return 1
  fi
  if [ -n "${TMUX:-}" ]; then
    tmux switch-client -t "$DL_SESSION"
  else
    tmux attach-session -t "$DL_SESSION"
  fi
}

dl-stop() {
  if ! _dl_exists; then
    echo "Not running."
    return 0
  fi
  if _dl_running; then
    tmux send-keys -t "$DL_SESSION" C-c
    # Wait up to 10s for the script to exit and print its summary
    for _ in $(seq 1 20); do
      _dl_running || break
      sleep 0.5
    done
    tmux capture-pane -p -t "$DL_SESSION" | grep "Stopped after" | tail -n 1
  fi
  tmux kill-session -t "$DL_SESSION"
  echo "Session '$DL_SESSION' closed."
}
