#!/bin/sh

# whatap-updater service (HP-UX)
# One-shot service that runs the agent patch script

export WHATAP_HOME=/usr/whatap/infra/conf
PATH=/sbin:/usr/sbin:/usr/bin:/usr/lib/netsvc:/usr/lib/netsvc/yp:/usr/sbin:/usr/bin:/usr/ccs/bin:/usr/contrib/bin:/usr/contrib/Q4/bin:/opt/perl/bin:/opt/ipf/bin:/opt/hparray/bin:/opt/nettladm/bin:/opt/fcms/bin:/opt/sas/bin:/opt/wbem/bin:/opt/wbem/sbin:/usr/bin/X11:/opt/resmon/bin:/usr/contrib/kwdb/bin:/opt/graphics/common/bin:/opt/sfm/bin:/opt/hpsmh/bin:/opt/upgrade/bin:/opt/gvsd/bin:/opt/sec_mgmt/bastille/bin:/opt/drd/bin:/opt/dsau/bin:/opt/dsau/sbin:/opt/firefox:/opt/gnome/bin:/opt/mozilla:/opt/perl_32/bin:/opt/perl_64/bin:/opt/sec_mgmt/spc/bin:/opt/ssh/bin:/opt/swa/bin:/opt/thunderbird:/opt/gwlm/bin:/usr/contrib/bin/X11:/opt/perf/bin:/opt/hp-gcc/bin:/sbin:/home/root

export PATH

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

    TMP_UPDATER="/tmp/whatap-updater.sh"
    cp "$UPDATER" "$TMP_UPDATER"
    chmod +x "$TMP_UPDATER"
    
    echo "Starting whatap-updater..."
    nohup /bin/sh "$TMP_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
