#!/usr/bin/env bash
# dewctl -- one front-end for running, watching and stopping DEW.
#
#   dewctl deploy all --broker server              install DEW on every node (once per materialization)
#   dewctl run <scenario.json> [more.json ...]   run (in sequence) and watch; ctrl-c stops
#   dewctl run <scenario.json> --only <label>     run only that Labels segment
#   dewctl run <scenario.json> --no-follow        start one and return immediately
#   dewctl status                     what every node did, last run
#   dewctl status -a                  all history, not just the last run
#   dewctl stop                       kill everything every node started
#   dewctl collect <remote-path>      pull that file from every node
#   dewctl expand <in> [-o <out>]     expand a scalable scenario
#   dewctl --version                  print the installed DEW version
#
# Reads ~/.dewrc, which `dewctl deploy` writes, so the broker and node list never
# have to be typed. Override any of it with environment variables, or point
# DEWRC somewhere else.
#
# This wraps deploy-dew.sh, run.py, stop.py, collect-dew.sh and
# expand-scenario.py rather than reimplementing them. Live progress comes from run.py, which listens to the
# broker; `status` reconstructs a finished run from the nodes' logs.
set -uo pipefail

RC="${DEWRC:-$HOME/.dewrc}"
# shellcheck disable=SC1090
[ -f "$RC" ] && . "$RC"

HERE="$(cd "$(dirname "$0")" && pwd)"
# Always this copy's own files. An older ~/.dewrc records the directory of
# whichever copy last deployed, which after switching to (or upgrading) the pip
# install would silently run stale code.
DEW_SPHERE="$HERE"
DEW_VENV="${DEW_VENV:-$HOME/dewenv}"
# The pip-installed dewctl passes the Python it was installed into. A git clone
# falls back to the install-xdc.sh venv, then the system python3.
PY="${DEW_PYTHON:-$DEW_VENV/bin/python3}"
[ -x "$PY" ] || PY="python3"

die() { echo "dewctl: $*" >&2; exit 1; }

dew_version() { sed -n 's/^__version__ = "\(.*\)"/\1/p' "$HERE/__init__.py"; }

# run.py and stop.py need pika. Say how to fix it here, rather than letting a
# fresh XDC fail with a bare ModuleNotFoundError traceback.
need_pika() {
    "$PY" -c "import pika" 2>/dev/null \
        || die "pika is not available to $PY. Install DEW with pip (see README), or from a git clone run install-xdc.sh."
}

usage() { sed -n '2,/^set /p' "$0" | sed '$d' | sed 's/^# \{0,1\}//'; }

need_config() {
    [ -n "${DEW_BROKER_HOST:-}" ] || die "no broker configured. Run \`dewctl deploy\`, or set DEW_BROKER_HOST."
    [ -n "${DEW_NODES:-}" ] || die "no node list configured. Run \`dewctl deploy\`, or set DEW_NODES=\"n1 n2\"."
}

# --- deploy -------------------------------------------------------------------

cmd_deploy() {
    bash "$DEW_SPHERE/deploy-dew.sh" "$@"
}

# --- run ----------------------------------------------------------------------

cmd_run() {
    local follow="--follow" only=""
    local scenarios=()
    while [ $# -gt 0 ]; do
        case "$1" in
            --no-follow) follow="--no-follow"; shift ;;
            --forever)   follow="--forever"; shift ;;
            --only)      only="$2"; shift 2 ;;
            -*) die "unknown option for run: $1" ;;
            *)  scenarios+=("$1"); shift ;;
        esac
    done
    [ "${#scenarios[@]}" -gt 0 ] || die "usage: dewctl run <scenario.json> [more.json ...] [--no-follow]"
    need_config
    need_pika

    # Several scenarios run in sequence -- setup, then the experiment, then
    # collect -- each to completion before the next. That requires watching each
    # one, so --no-follow is only meaningful for a single scenario.
    if [ "${#scenarios[@]}" -gt 1 ] && [ "$follow" = "--no-follow" ]; then
        die "multiple scenarios run in sequence and need watching; drop --no-follow"
    fi

    local i=0 total="${#scenarios[@]}" scen rc
    for scen in "${scenarios[@]}"; do
        i=$((i + 1))
        [ -f "$scen" ] || die "no such file: $scen"
        [ "$total" -gt 1 ] && echo "=== phase $i/$total: $scen ==="

        # A scenario with a non-empty Constraints block is written against roles
        # and has to be expanded first. Running one unexpanded quietly does
        # nothing useful, so catch it here.
        if "$PY" -c "import json,sys; sys.exit(0 if json.load(open(sys.argv[1])).get('Constraints') else 1)" "$scen" 2>/dev/null; then
            local out
            out="$(mktemp /tmp/dew-expanded-XXXXXX.json)"
            "$PY" "$DEW_SPHERE/expand-scenario.py" "$scen" -o "$out" || exit 1
            echo "using expanded scenario: $out"
            scen="$out"
        fi

        # Follow by default here, unlike run.py itself: at the dewctl level the
        # question is "run this and show me what happens".
        if [ -n "$only" ]; then
            DEW_BROKER_HOST="$DEW_BROKER_HOST" "$PY" "$DEW_SPHERE/run.py" --only "$only" "$follow" "$scen"
        else
            DEW_BROKER_HOST="$DEW_BROKER_HOST" "$PY" "$DEW_SPHERE/run.py" "$follow" "$scen"
        fi
        rc=$?
        # In a sequence a failed/aborted phase stops the rest -- do not run the
        # experiment if setup failed. A single run keeps its old exit behaviour.
        if [ "$total" -gt 1 ] && [ "$rc" -ne 0 ]; then
            die "phase $i ($scen) exited $rc; stopping the sequence"
        fi
    done
}

# --- status -------------------------------------------------------------------
#
# Reconstructed from each agent's log rather than queried, because nothing
# outside the nodes records run state. TASK / STARTED / FINISHED lines give:
#   declared, never started   -> blocked, and the line says on what
#   started, not finished     -> running now
#   finished with rc != 0     -> failed
#
# Every run begins with an `init` message that every agent logs, so by default
# only lines after the last one are considered. That makes this "this run"
# rather than a guessed tail of an append-only file.
#
# The marker has to be `init`, not `start`: the agent parses the scenario on
# init and prints its TASK lines immediately, *before* the start message
# arrives. Resetting on start would discard the very lines this needs.

status_awk='
/Received msg .init / { if (!ALL) { delete tsk; delete whn; delete act; delete sta; delete fin; delete rc } }
/^TASK /     { id=$2; tsk[id]=1
               for (i=3;i<=NF;i++) {
                   if (substr($i,1,5)=="when=")   whn[id]=substr($i,6)
                   if (substr($i,1,7)=="action=") act[id]=substr($i,8)
               } }
/^STARTED /  { sta[$2]=1 }
/^FINISHED / { fin[$2]=1; rc[$2]=substr($3,4) }
END {
    n=0
    for (id in tsk) {
        if (id in fin) {
            if (rc[id] != "0")
                printf "  %-9s task%-4s %s (rc=%s)\n", "FAILED", id, act[id], rc[id]
            else
                printf "  %-9s task%-4s %s\n", "done", id, act[id]
        } else if (id in sta) {
            printf "  %-9s task%-4s %s\n", "running", id, act[id]
            pending++
        } else {
            printf "  %-9s task%-4s %s -- waiting on %s\n", "blocked", id, act[id], whn[id]
            pending++
        }
        n++
    }
    if (n == 0) print "  (no tasks for this node in this run)"
    # Machine-readable trailer, stripped before display. The follow loop needs to
    # tell "finished" from "still going", and counting printed lines would break
    # the moment the wording changes.
    printf "##counts %d %d\n", n, pending+0
}'

# Sets TOTAL_TASKS and TOTAL_PENDING for the caller.
show_status() {
    local all="$1" n out counts
    TOTAL_TASKS=0
    TOTAL_PENDING=0
    printf 'broker: %s\n\n' "$DEW_BROKER_HOST"
    for n in $DEW_NODES; do
        # One ssh per node, not two. Each command substitution runs in a
        # subshell, and a ctrl-c that lands there is absorbed by the dying child
        # instead of reaching this script -- so halving the round trips halves
        # the window in which an interrupt looks ignored. Service state is the
        # first line, the log is the rest.
        out="$(ssh -n -o ConnectTimeout=5 "$n" \
                 'systemctl is-active dew-agent 2>/dev/null || echo unknown
                  tail -2000 /tmp/dew-agent.log 2>/dev/null' 2>/dev/null)"
        if [ -z "$out" ]; then
            printf '%-10s %s\n' "$n" "unreachable"
            continue
        fi
        printf '%-10s %s\n' "$n" "$(printf '%s\n' "$out" | head -1)"
        out="$(printf '%s\n' "$out" | tail -n +2 | awk -v ALL="$all" "$status_awk")"
        counts="$(printf '%s\n' "$out" | sed -n 's/^##counts //p')"
        [ -n "$counts" ] || counts="0 0"
        printf '%s\n' "$out" | grep -v '^##counts '
        TOTAL_TASKS=$(( TOTAL_TASKS + ${counts%% *} ))
        TOTAL_PENDING=$(( TOTAL_PENDING + ${counts##* } ))
    done
}

# Deliberately one-shot. The follow mode that used to live here polled six
# nodes over ssh every two seconds and redrew the screen, which meant it
# depended on `clear` behaving and on ctrl-c reaching a bash trap through a
# command substitution -- neither of which holds in an XDC shell that inherits
# SIGINT as SIG_IGN. `dewctl run` watches a live run from the broker instead,
# so this is left for the thing it is genuinely good at: inspecting a run after
# the fact, which the watcher cannot do because it only sees messages while it
# is attached.
cmd_status() {
    need_config
    local all=0
    while [ $# -gt 0 ]; do
        case "$1" in
            -a|--all) all=1; shift ;;
            -f|--follow|--forever)
                die "status no longer follows -- use \`dewctl run\`, which watches the run it starts." ;;
            *) die "unknown option for status: $1" ;;
        esac
    done
    show_status "$all"
}

# --- stop / collect / expand --------------------------------------------------

cmd_stop() {
    need_config
    need_pika
    DEW_BROKER_HOST="$DEW_BROKER_HOST" "$PY" "$DEW_SPHERE/stop.py" all all
}

cmd_collect() {
    need_config
    local path="${1:-}"; shift || true
    [ -n "$path" ] || die "usage: dewctl collect <remote-path> [-o <dir>]"
    # shellcheck disable=SC2086
    bash "$DEW_SPHERE/collect-dew.sh" "$path" $DEW_NODES "$@"
}

cmd_expand() {
    [ $# -gt 0 ] || die "usage: dewctl expand <scenario.json> [-o <out>]"
    "$PY" "$DEW_SPHERE/expand-scenario.py" "$@"
}

# --- dispatch -----------------------------------------------------------------

sub="${1:-}"
[ $# -gt 0 ] && shift
case "$sub" in
    deploy)   cmd_deploy "$@" ;;
    run)      cmd_run "$@" ;;
    status)   cmd_status "$@" ;;
    stop)     cmd_stop "$@" ;;
    collect)  cmd_collect "$@" ;;
    expand)   cmd_expand "$@" ;;
    -V|--version) echo "dewctl $(dew_version)" ;;
    ""|-h|--help) usage ;;
    *)        die "unknown command: $sub (try --help)" ;;
esac
