#!/bin/sh
#
# Copyright (c) 2023 Ken McDonell.  All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# Wrapper script to start or Stop the Performance Co-Pilot pmproxy
# process.  The real work is done in $PCP_SYSCONF_DIR/pmproxy/rc.
#
# The following is for chkconfig on RedHat based systems
# chkconfig: 2345 95 05
# description: pmproxy is the pmcd proxy daemon for the Performance Co-Pilot (PCP)
#
# The following is for insserv(1) based systems,
# e.g. SuSE, where chkconfig is a perl script.
### BEGIN INIT INFO
# Provides:       pmproxy
# Required-Start: $remote_fs
# Should-Start: $local_fs $network $syslog $time $pmcd
# Required-Stop: $remote_fs
# Should-Stop:  $local_fs $network $syslog $pmcd
# Default-Start:  2 3 4 5
# Default-Stop:   0 1 6
# Short-Description: Control pmproxy (the pmcd proxy daemon for PCP)
# Description:       Configure and control pmproxy (the pmcd proxy daemon for the Performance Co-Pilot)
### END INIT INFO
#
# For FreeBSD
# PROVIDE: pmproxy
# REQUIRE: NETWORKING FILESYSTEMS pmcd
# KEYWORD: shutdown
# And add the following lines to /etc/rc.conf to run pmproxy:
# pmproxy_enable="YES"
#

. $PCP_DIR/etc/pcp.env

if [ `id -u` -ne 0 ]
then
    echo "$0: Error: You must be root (uid 0) to start or stop pmproxy via this script"
    exit 1
fi

# Handle setup for transients that might be lost after reboot,
# e.g. $PCP_RUN_DIR
#
$PCP_BINADM_DIR/pcp-reboot-init

# paranoid defaults if something goes wrong ...
[ -z "$PCP_USER" ] && PCP_USER=pcp
[ -z "$PCP_GROUP" ] && PCP_USER=pcp

# if we're called with -v (or any other command line option) this is
# an arg for our "rc" script, not setpriv(1) or runuser(1)
export POSIXLY_CORRECT=true

# do the real startup as user pcp:pcp
#
if which setpriv >/dev/null 2>&1
then
    uid=`id -u $PCP_USER`
    gid=`id -g $PCP_GROUP`
    setpriv --clear-groups --reuid=$uid --regid=$gid \
	$PCP_SYSCONF_DIR/pmproxy/rc "$@"
elif which runuser >/dev/null 2>&1
then
    runuser -s /bin/sh -g $PCP_GROUP $PCP_USER $PCP_SYSCONF_DIR/pmproxy/rc "$@"
else
    $PCP_BINADM_DIR/runaspcp "$PCP_SYSCONF_DIR/pmproxy/rc $*"
fi

exit $?
