#!/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")"
ip netns exec $NAME nsenter -t $RSPID -p -m -i -u /bin/sh \
   -x -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

# Delete host side virtual cabling interfaces
N=0
for C in $CABLES ; do
    MAC="${C#*=}"
    [ "$MAC" ] && [ -z "${MAC%%.*}" ] && continue # ignore vlan cabling
    ip link del dev "$NAME$N"
    N=$((N+1))
done

# Delete then netns itf remaining
ip netns del $NAME

true
