#!/usr/bin/env bash
set -euo pipefail

SCRIPT=/root/whp/scripts/customer-container-watchdog.sh
LOCK=/run/whp-customer-watchdog.lock
LOG=/var/log/whp/customer-watchdog.log
TIMEOUT_SECS=50

mkdir -p /var/log/whp
chmod 0755 /var/log/whp

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TARBALL_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
SRC="$TARBALL_ROOT/scripts/customer-container-watchdog.sh"
LIB_SRC="$TARBALL_ROOT/scripts/lib-container-tiers.sh"

if [ -f "$SRC" ]; then install -m 0755 "$SRC" "$SCRIPT"; fi
if [ -f "$LIB_SRC" ]; then install -m 0644 "$LIB_SRC" /root/whp/scripts/lib-container-tiers.sh; fi
if [ ! -x "$SCRIPT" ]; then echo "FATAL: $SCRIPT missing"; exit 1; fi

LINE="* * * * * /usr/bin/flock -n ${LOCK} /usr/bin/timeout ${TIMEOUT_SECS} ${SCRIPT} >>${LOG} 2>&1"
TMP=$(mktemp); trap 'rm -f "$TMP" "$TMP.new"' EXIT
crontab -l 2>/dev/null > "$TMP" || true
if grep -F "$SCRIPT" "$TMP" >/dev/null 2>&1; then
    grep -vF "$SCRIPT" "$TMP" > "$TMP.new"
    mv "$TMP.new" "$TMP"
fi
echo "$LINE" >> "$TMP"
crontab "$TMP"
echo "Installed cron: $LINE"
