#!/bin/sh
#
# : /usr/local/etc/rc.d/dssystem
#

# PROVIDE: ds-system
# REQUIRE: NETWORKING LOGIN
# KEYWORD: shutdown

: ${dssystem_enable="NO"}

dssystem_prestart()
{
    env_file="/etc/iocage-env"
    grep -q "NETWORKING_MODE=nat" "${env_file}"
    if [ $? = 0 ]; then
        ip=$(cat "${env_file}" | grep "HOST_ADDRESS=" | cut -d "=" -f 2)
        nat_fwd=$(cat "${env_file}" | grep "NAT_FORWARDS=" | cut -d "=" -f 2)
        for rule in $(echo $nat_fwd | sed "s/,/ /g") ; do
            echo "${rule}" | grep -q "(80:"
            if [ $? = 1 ]; then
                continue
            fi
            port=":$(echo "${rule}" | cut -d ':' -f 2 | cut -d ')' -f 1)"
            break
        done
        echo "${ip}${port}" > /root/dhcpip
    else
        netstat -nr | grep lo0 | grep -v '::' | grep -v '127.0.0.1' | awk '{print $1}' | head -n 1 > /root/dhcpip
    fi
    IP=`cat /root/dhcpip`
    sed -i.bak -E "s|codebase=\"(.+)\"|codebase=\"http://$IP/asigra/\"|" /usr/local/www/asigra/DSOP.jnlp
    rm -f /usr/local/www/asigra/DSOP.jnlp.bak

    dssys_file="/etc/dssys.cfg"
    # We make sure that the port is not added to the IP Address
    ip=$(echo ${IP} | cut -d':' -f1)
    grep -q "^External IP Addr.*:" "${dssys_file}"
    if [ $? -eq 0 ]; then
        sed -ie "s/\(External IP Addr\)\([ ]*\)\(.*\)/\1\2: ${ip}/" ${dssys_file}
    else
        echo "External IP Addr : ${ip}" >> ${dssys_file}
    fi
}

dssystem_stop()
{
	pids="`pgrep -j none dssystem_dc`"
	if [ -n "$pids" ];then
		for i in $pids;do
			kill -s TERM "$i"
		done
	fi

	pwait -t 15s $pids 2> /dev/null
	if [ $? -eq 124 ]; then
		pids="`pgrep -j none dssystem_dc`"
		if [ -n "$pids" ];then
			for i in $pids;do
				kill -9 "$i"
			done
		fi
	fi
}

. /etc/rc.subr
name="dssystem"
rcvar="dssystem_enable"
command=/usr/local/ds-system/dssystem_dc
dssystem_flags="--daemon --lang en"
sig_stop="TERM"
load_rc_config $name
start_precmd=dssystem_prestart
stop_cmd=dssystem_stop
run_rc_command "$1"

