#!/bin/sh

date1="$6-$5-$4 $3:$2:00"
datenow="$(date +%s)"
dateset="$(date -d "$date1" +%s)"

CFG_FILE=/etc/ipsec.d/grocx.conf
modify_ipsec_cfgfile() {
        cat $CFG_FILE | grep -q -e "auto=start #$2" -e "auto=route #$2" || return 1

        local str=$(cat $CFG_FILE | grep -m 1 " #$2")
        local route=$(cat $CFG_FILE | grep " #$2" | grep -q "route" && echo 1 )
        local auto

        if [ "$route" == "1"  ] ; then
                auto="auto=route"
        else
                auto="auto=start"
        fi

        case "$1" in
                4)      #vpn up
                        sed 's/'"$str"'/'"\t$auto #$2"'/' $CFG_FILE > /tmp/ipsec.conf
                ;;
                5)      #vpn down
                        sed 's/'"$str"'/'"\t#$auto #$2"'/' $CFG_FILE > /tmp/ipsec.conf
                ;;
        esac
        test -s /tmp/ipsec.conf && cp /tmp/ipsec.conf $CFG_FILE

        [ "$1" == "5" ] && {
                ipsec whack --delete --name "T$2"
                return
        }

        /usr/sbin/ipsec auto --rereadsecrets
		/usr/sbin/ipsec auto --replace "T$2"
        if [ "$route" == "1"  ] ; then
                ipsec whack --route --name "T$2"
        else
                ipsec whack --name "T$2" --initiate
        fi
}

if [ $datenow -gt $dateset ] ;then
        case "$1" in
                0)
                        logger "[schedule] WAN Up"
						uci set network.wan.disable=0
						uci commit network
                        . /sbin/ifup wan
                ;;
                1)
                        logger "[schedule] WAN Down"
						uci set network.wan.disable=1
						uci commit network
                        . /sbin/ifdown wan
                ;;
                2)
                        logger "[schedule] Wireless On"
                        uci set wireless.ra0.radio=1
                        uci commit wireless
                        . /sbin/wifi up
                ;;
                3)
                        logger "[schedule] Wireless Off"
                        uci set wireless.ra0.radio=0
                        uci commit wireless
                        . /sbin/wifi up
                ;;
				4|5)	# vpn up or vpn down
                        logger "[schedule] VPN:$7 $1 (4:Up/5:Down)"
						modify_ipsec_cfgfile $1 $7
                ;;
                6)
                        logger "[schedule] bt On"
                        . /sbin/bt up
                ;;
                7)
                        logger "[schedule] bt Off"
                        . /sbin/bt down
                ;;
				8)
						logger "[schedule] Auto Reboot"
						reboot
				;;
        esac
fi