#!/bin/sh

umask 066 # user read/write

separator() {
    echo "*************************************** $*"
}

err () {
    separator ERROR 1>&2
    echo "`basename $0`: $@" 1>&2
    exit 1
}

TMPDIR=~/.arb_tmp/tmp
mkdir -p $TMPDIR
chooser="$TMPDIR/arb_pids_${USER}_*"

separator PANIC
echo "  This Module tries to save a running database"
echo "  There may be more than one database server (ARB_NT):"
echo "          --------------------------------"

for i in $chooser ; do
    if [ ! -L "$i" ] ; then
        /bin/echo "             - >" `ls $i` "<";
    fi
done
echo "          --------------------------------"

separator
echo "Please choose one line and enter the rightmost number"

read ARB_PID
if [ ! -f $TMPDIR/arb_pids_${USER}_${ARB_PID} ]; then
    err "Incorrect Choice"
fi

separator
echo "Please enter full path (to save DB):"
read FILE

panicfile="$TMPDIR/arb_panic_${USER}_${ARB_PID}"
rm -f $panicfile
echo "$FILE" >$panicfile
ok=false
for i in `cat $TMPDIR/arb_pids_${USER}_${ARB_PID}`; do
    echo "[Sending SIGHUP to pid $i]"
    if kill -HUP $i 2>/dev/null; then
        ok=true
        echo "[Process $i accepted HUP]"
        break
    fi
done

if [ "$ok" = "false" ]; then
    err "Sorry could not find a running server"
fi
separator
echo "Wait until database is saved (or press <ctrl-c> to abort)"
while [ -f $panicfile ]; do
    echo "[waiting]"
    sleep 1
    if [ -f $panicfile] ; then
        sleep 1
        if [ -f $panicfile] ; then
            sleep 1
            if [ -f $panicfile] ; then
                sleep 1
                if [ -f $panicfile] ; then
                    sleep 1        
                fi
            fi
        fi
    fi
done

separator
echo "enter 'kill'    if you want to kill the server and its clients"
echo "enter 'killall' if you want to kill ALL servers and clients"

read ki

if [ "$ki" = "kill" ] ; then
    echo "[Sending SIGTERM to pid $i]"
    kill -TERM $i
fi
if [ "$ki" = "killall" ] ; then
    arb_clean killall
fi