#!/sbin/sh
#
# whatap-updater service (Solaris)
# One-shot service that runs the agent patch script

WHATAP_HOME=/usr/whatap/infra/conf
export WHATAP_HOME

UPDATER=/usr/whatap/infra/infra_agent_patch.sh
ENVFILE=/usr/whatap/infra/whatap.env
LOG=/var/log/whatap-updater.log
PID=/var/run/whatap-updater.pid

whatap_updater_start() {
    if [ ! -x "$UPDATER" ]; then
        echo "$UPDATER not found or not executable"
        exit 1
    fi

    if [ ! -f "$ENVFILE" ]; then
        echo "$ENVFILE not found"
        exit 1
    fi

    echo "Starting whatap-updater..."
    nohup "$UPDATER" "$ENVFILE" >> "$LOG" 2>&1 &
    echo $! > "$PID"
    echo "whatap-updater started (PID $!)"
}

whatap_updater_stop() {
    echo "Stopping whatap-updater..."
    if [ -f "$PID" ]; then
        kill -TERM `cat "$PID"` 2>/dev/null
        rm -f "$PID"
    fi
    echo "whatap-updater stopped"
}

case "$1" in
    start)
        whatap_updater_start
        ;;
    stop)
        whatap_updater_stop
        ;;
    restart)
        whatap_updater_stop
        whatap_updater_start
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac
