#!/bin/sh
#
# Script to stop the nominated overlay subhost

OVERLAYDIR="$(dirname $(realpath $0))"
. $OVERLAYDIR/functions $*

subhost_name "$1"
subhost_config

read USPID RSPID <<EOF
$(is_live $NAME)
EOF

if [ -z "$USPID" ] ; then
    [ -r /run/netns/$NAME ] && ip netns del $NAME
    echo "$NAME is not running" >&2
    exit 1
fi

if [ -z "$RSPID" ] ; then
    cat <<EOF >&2
***  $NAME is started (pid $USPID) but doesn't seem to be running
*** /.reaper and might need manual fixing.
EOF
    exit 1
fi

START="$(reverse "$START")"
nsenter -t $RSPID -p -m -i -u \
	ip netns exec $NAME chroot $(realpath $LIVE) \
	/bin/sh -c "for srv in $START ; do service \$srv stop ; done"

for p in $RSPID $USPID ; do
    for S in 15 1 2 9 ; do
	ps -hocmd $p || break
	kill -$S $p
    done
done

[ -r /run/netns/$NAME ] && ip netns del $NAME

true
