#!/bin/sh

PKGSTATUSFILE=/etc/zyxel/pkg_conf/status
PKGNAME=AuroraSyncBackup
PKGPATH=$(grep ${PKGNAME} ${PKGSTATUSFILE} | grep "Installed-Rule" | awk -F":" '{print $2}' | sed 's/\/$//g' | sed 's/ //g')

CONTROLFILE="${PKGPATH}/zypkg_conf/info/${PKGNAME}.control"

# add pkg status flag file
STATUS_FILE=${PKGPATH}/share/pkg_status

start_ipcam_viewer() {
	# get vendor device list?
	# modify cron table: add retrieve_all_ipcam_recording_to_NAS.py, execute every 10 minutes from now
	/bin/crontab -l | /bin/grep -v 'retrieve_all_ipcam_recording_to_NAS.py' > /tmp/ipcam_crontab
	minute=$(/bin/date +"%M" | /bin/cut -c2)
	echo "$minute,1$minute,2$minute,3$minute,4$minute,5$minute * * * * /sbin/start-stop-daemon -b -S -N 5 -m -p /var/run/retrieve_all_ipcam_recording_to_NAS.pid -a ${PKGPATH}/scripts/retrieve_all_ipcam_recording_to_NAS.py > /dev/null 2>&1" >> /tmp/ipcam_crontab
	/bin/crontab /tmp/ipcam_crontab
}

stop_ipcam_viewer() {
	# modify cron table: remove retrieve_all_ipcam_recording_to_NAS.py
	/bin/crontab -l | /bin/grep -v 'retrieve_all_ipcam_recording_to_NAS.py' > /tmp/ipcam_crontab
	/bin/crontab /tmp/ipcam_crontab
	# stop process
	start-stop-daemon -K -p /var/run/retrieve_all_ipcam_recording_to_NAS.pid > /dev/null 2>&1
	rm -f /var/run/retrieve_all_ipcam_recording_to_NAS.pid > /dev/null 2>&1
}

if [ "$1" == "get_ipcam_info" ]; then
	${PKGPATH}/scripts/get_ipcam_info.py
elif [ "$1" == "set_ipcam_info" ]; then
	${PKGPATH}/scripts/set_ipcam_info.py "$2"
elif [ "$1" == "init_general_settings" ]; then
	${PKGPATH}/scripts/init_general_settings.py
elif [ "$1" == "startup" ]; then
	start_ipcam_viewer
elif [ "$1" == "shutdown" ]; then
	stop_ipcam_viewer 
elif [ "$1" == "getlink" ]; then
	echo "ipcamWin"
elif [ "$1" == "status" ]; then
	echo "Built-in"
elif [ "$1" == "version" ]; then
	VERSION=`grep "Version:" ${CONTROLFILE} | awk -F "zypkg" '{print $2}'`
	return ${VERSION}
fi

exit 0

