#!/bin/sh

OPENSSL=$(which openssl)
CRT_FILE=/tmp/secure/etc/lighttpd/certs/server.pem

get_time()
{
	#Get Month
	Month=$1
	if [ "$Month" == "Jan" ]; then
		MM=01
	elif [ "$Month" == "Feb" ]; then
		MM=02
	elif [ "$Month" == "Mar" ]; then
		MM=03
	elif [ "$Month" == "Apr" ]; then
		MM=04
	elif [ "$Month" == "May" ]; then
		MM=05
	elif [ "$Month" == "Jun" ]; then
		MM=06
	elif [ "$Month" == "Jul" ]; then
		MM=07
	elif [ "$Month" == "Aug" ]; then
		MM=08
	elif [ "$Month" == "Sep" ]; then
		MM=09
	elif [ "$Month" == "Oct" ]; then
		MM=10
	elif [ "$Month" == "Nov" ]; then
		MM=11
	elif [ "$Month" == "Dec" ]; then
		MM=12
	fi
	#Get daily
	daily_old=$2
	if [ $daily_old -lt 10 ];then
		daily="0$daily_old"
	else
		daily=$daily_old
	fi
	echo "$MM$daily" > /tmp/monday.txt
}

time_check() {
	END_TIME=`openssl x509 -in $CRT_FILE -noout -enddate |awk -F"=" '{print $2}'`
	END_TIME_Year=`echo $END_TIME|cut -d " " -f 4`
	END_TIME_Month=`echo $END_TIME|cut -d " " -f 1`
	END_TIME_Daily=`echo $END_TIME|cut -d " " -f 2`
	get_time $END_TIME_Month $END_TIME_Daily 
	echo "$END_TIME_Year$(cat /tmp/monday.txt)" > /tmp/end_time.txt

	NOW_TIME=`date`
	NOW_TIME_Year=`echo $NOW_TIME|cut -d " " -f 6`
	NOW_TIME_Month=`echo $NOW_TIME|cut -d " " -f 2`
	NOW_TIME_Daily=`echo $NOW_TIME|cut -d " " -f 3`
	get_time $NOW_TIME_Month $NOW_TIME_Daily 
	echo "$NOW_TIME_Year$(cat /tmp/monday.txt)" > /tmp/now_time.txt
}

start() {
	#https_cert start
	[ -d '/tmp/mnt/ntgr/https_cert' ] && rm -rf '/tmp/mnt/ntgr/https_cert'

	#check if cert exist and cert is out of date
	if [ ! -e "/tmp/secure/etc/lighttpd/certs/server.pem" ] || [ "x$(/bin/config get https_self_signed)" != "x1" ];then
		flag=1
	else
		time_check
		END_TIME1=$(cat /tmp/end_time.txt)
		NOW_TIME1=$(cat /tmp/now_time.txt)
		rm -rf /tmp/monday.txt /tmp/end_time.txt /tmp/now_time.txt
		if [ $NOW_TIME1 -ge $END_TIME1 ]; then
			flag=1
		fi
	fi

	if [ "x$flag" = "x1" ];then
		cd /etc/lighttpd/certs/
		./https_cert.sh
		[ ! -d '/tmp/secure/etc/lighttpd/certs' ] && mkdir -p '/tmp/secure/etc/lighttpd/certs'
		mv /etc/lighttpd/certs/server.pem /tmp/secure/etc/lighttpd/certs/
		rm -rf /tmp/secure/etc/lighttpd/certs/https_cert.sh
		/bin/config set https_self_signed=1
	fi
}

case "$1" in
	start)
	start
	;;
esac
