#!/bin/sh -e
#DEBHELPER#

# figure out what sort if init|systemctl|... we're using to
# launch daemons and services
do_systemctl=false
if which systemctl >/dev/null 2>&1
then
    # we have a systemctl executable, but it might be disabled,
    # e.g. on MX Linux or in a container with no systemd running
    systemctl whoami >/dev/null 2>&1 && do_systemctl=true
fi
do_systemd_helper=false
if $do_systemctl
then
    which deb-systemd-helper >/dev/null 2>&1 && do_systemd_helper=true
fi
do_sysv=false
if which update-rc.d >/dev/null 2>&1
then
    if which invoke-rc.d >/dev/null 2>&1
    then
	if which runlevel >/dev/null 2>&1
	then
	    if runlevel >/dev/null 2>&1
	    then
		# System-V init installed and running
		do_sysv=true
	    fi
	fi
    fi
fi

# only need to check pmcd.service, if it is here they will all
# be here
if [ -f /lib/systemd/system/pmcd.service ]
then
    :
else
    do_systemctl=false
    do_systemd_helper=false
fi
# ditto for the System-V variant for pmlogger
if [ -f /etc/init.d/pmlogger ]
then
    :
else
    do_sysv=false
fi

if $do_systemctl
then
    systemctl stop pmlogger.service >/dev/null
    systemctl stop pmcd.service >/dev/null
elif $do_sysv
then
    for svc in pmproxy pmie pmlogger pmcd
    do
	if invoke-rc.d $svc stop
	then
	    :
	else
	    echo >&2 "pcp.prerm: Warning: invoke-rc.d $svc stop failed"
	fi
    done
else
    for svc in pmproxy pmie pmlogger pmcd
    do
	if /etc/init.d/$svc stop
	then
	    :
	else
	    echo >&2 "pcp.prerm: Warning: /etc/init.d/$svc stop failed"
	fi
    done
fi

rm -f /var/lib/pcp/pmns/.NeedRebuild
rm -f /var/log/pcp/pmlogger/.NeedRewrite
