#!/bin/bash

. /etc/profile

#################################
# MAIN
#################################

systemtype=$1
shift
alltargets="$*"

echo $systemtype > /etc/fsshr.system.type

touch /run/fsshr-generic.service.alive
rm -f /run/fsshr-generic.service.fancy.wait
mkfifo /run/fsshr-generic.service.fancy.wait

#start all server instances for incoming command requests
for atgt in $alltargets ; do
    mkdir -p /var/fsshr/$atgt/$systemtype
    cd /var/fsshr/$atgt/$systemtype
    fsshr --start
done

uptimesec=0

while [ -e /run/fsshr-generic.service.alive ]; do

    #act like a periodic timer so that we can add custom things to be executed inside this loop
    (
        [ -d /etc/fsshr-loop-hooks.d ] || exit 0
        cd /etc/fsshr-loop-hooks.d
        for aprog in $(ls -1) ; do
            #also pass a kind of "service-uptime" in seconds in order to help the hook realize when and what ... especially useful for late initialization stuff
            [ -x $aprog ] && ./$aprog $uptimesec
        done
    )

    (
        exec 123<>/run/fsshr-generic.service.fancy.wait
        for i in {0..9}; do
            #sleep in a fancy way without spawning processes
            read -t 1 dummy <&123
            #if alive flag file does not exist then it means we got a stop indication
            [ -e /run/fsshr-generic.service.alive ] || exit 0
        done
        exit 1
    ) && break
    
    uptimesec=$(($uptimesec + 10))
    
    #check and restart dead instances
    for atgt in $alltargets ; do
        cd /var/fsshr/$atgt/$systemtype
        fsshr --status || fsshr --start
    done
done

#stop all instances
for atgt in $alltargets ; do
    cd /var/fsshr/$atgt/$systemtype
    fsshr --stop
done

exit 0
