#!/usr/bin/env bash
# Install the AWOOOI cold-start textfile monitor on host 110 using the wooo user cron.
#
# This installer does not require sudo. It copies read-only monitor scripts into
# /home/wooo/scripts and maintains a marked crontab block.

set -euo pipefail

TARGET_HOST="${TARGET_HOST:-wooo@192.168.0.110}"
REMOTE_SCRIPT_DIR="${REMOTE_SCRIPT_DIR:-/home/wooo/scripts}"
REMOTE_TEXTFILE_DIR="${REMOTE_TEXTFILE_DIR:-/home/wooo/node_exporter_textfiles}"
REMOTE_LOG_DIR="${REMOTE_LOG_DIR:-/home/wooo/reboot-recovery}"
CRON_SCHEDULE="${CRON_SCHEDULE:-*/10 * * * *}"
CHECK_TIMEOUT_SECONDS="${CHECK_TIMEOUT_SECONDS:-240}"

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
CHECK_SCRIPT="$SCRIPT_DIR/full-stack-cold-start-check.sh"
EXPORTER_SCRIPT="$SCRIPT_DIR/cold-start-textfile-exporter.sh"

if [ ! -f "$CHECK_SCRIPT" ] || [ ! -f "$EXPORTER_SCRIPT" ]; then
  echo "Required scripts not found beside installer" >&2
  exit 66
fi

ssh "$TARGET_HOST" "mkdir -p '$REMOTE_SCRIPT_DIR' '$REMOTE_TEXTFILE_DIR' '$REMOTE_LOG_DIR'"
scp "$CHECK_SCRIPT" "$TARGET_HOST:$REMOTE_SCRIPT_DIR/full-stack-cold-start-check.sh"
scp "$EXPORTER_SCRIPT" "$TARGET_HOST:$REMOTE_SCRIPT_DIR/cold-start-textfile-exporter.sh"
ssh "$TARGET_HOST" "chmod 0755 '$REMOTE_SCRIPT_DIR/full-stack-cold-start-check.sh' '$REMOTE_SCRIPT_DIR/cold-start-textfile-exporter.sh'"

ssh "$TARGET_HOST" bash -s <<REMOTE
set -euo pipefail
tmp=\$(mktemp)
crontab -l 2>/dev/null | sed '/# AWOOOI cold-start monitor start/,/# AWOOOI cold-start monitor end/d' > "\$tmp" || true
cat >> "\$tmp" <<'CRON'
# AWOOOI cold-start monitor start
$CRON_SCHEDULE PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin CHECK_SCRIPT=$REMOTE_SCRIPT_DIR/full-stack-cold-start-check.sh TEXTFILE_DIR=$REMOTE_TEXTFILE_DIR LOG_DIR=$REMOTE_LOG_DIR CHECK_TIMEOUT_SECONDS=$CHECK_TIMEOUT_SECONDS $REMOTE_SCRIPT_DIR/cold-start-textfile-exporter.sh >/tmp/awoooi-cold-start-monitor.cron.log 2>&1
# AWOOOI cold-start monitor end
CRON
crontab "\$tmp"
rm -f "\$tmp"
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin CHECK_SCRIPT=$REMOTE_SCRIPT_DIR/full-stack-cold-start-check.sh TEXTFILE_DIR=$REMOTE_TEXTFILE_DIR LOG_DIR=$REMOTE_LOG_DIR CHECK_TIMEOUT_SECONDS=$CHECK_TIMEOUT_SECONDS "$REMOTE_SCRIPT_DIR/cold-start-textfile-exporter.sh"
test -s "$REMOTE_TEXTFILE_DIR/cold_start_recovery.prom"
tail -40 "$REMOTE_TEXTFILE_DIR/cold_start_recovery.prom"
REMOTE
