#!/bin/sh
#
# a workaround for the sucking date behavior of doscam, oscam and ncam
#

. /etc/init.d/globals

BINARY="/var/bin/$2"
FLAGFILE="/var/etc/.$2"

case "$1" in
	"start")
		if [ ! -e /etc/date-dummy ]; then
			SHOWINFO "can't work. /etc/date-dummy is missing"
			exit 1
		fi

		DATE_DUMMY=$(cat /etc/date-dummy)
		DATE_TODAY=$(date +%Y%m%d%H%M)

		if [ "${DATE_TODAY:0:8}" = "${DATE_DUMMY:0:8}" ]; then
			# try to read date from flagfile
			test -e $FLAGFILE && \
			DATE_FLAG=$(date -r $FLAGFILE +%Y%m%d%H%M)

			# try to read date from binary
			DATE_CAMD=$(strings $BINARY | grep -B1 "is smaller than the build date")
			DATE_CAMD=${DATE_CAMD:0:11}
			_m=$(echo $DATE_CAMD | cut -d\  -f1)
			_d=$(echo $DATE_CAMD | cut -d\  -f2)
			_y=$(echo $DATE_CAMD | cut -d\  -f3)

			c=0
			for m in Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec; do
				c=$(($c+1))
				if [ "$m" = "$_m" ]; then
					_m=$c
					break
				fi
			done

			test ${#_m} -lt 2 && _m=0$_m
			test ${#_d} -lt 2 && _d=0$_d

			DATE_CAMD=$_y$_m$_d

			# try to read date from versionfile
			DATE_IMAGE=$(cat /.version | grep "^version=" | cut -d= -f2)
			DATE_IMAGE=${DATE_IMAGE:4}

			c=0
			for date in "$DATE_FLAG" "$DATE_CAMD" "$DATE_IMAGE"; do
				c=$(($c+1))
				while [ ${#date} -lt 12 ]; do
					date=$date"0"
				done
				test $c = 1 && DATE_FLAG=$date
				test $c = 2 && DATE_CAMD=$date
				test $c = 3 && DATE_IMAGE=$date
			done

			SHOWINFO "manipulating date ... "
			for date in "$DATE_FLAG" "$DATE_CAMD" "$DATE_IMAGE"; do
				echo $date;
			done | sort -r -u | while read date; do
				if date -s $date > /dev/null; then
					SHOWINFO "done ($date)"
					break
				else
					continue
				fi
				SHOWWARN "failed"
			done
		fi
	;;
	"stop")
		test -e $FLAGFILE && touch $FLAGFILE
	;;
	*)
		echo "[$BASENAME] Usage: $0 {start|stop}"
	;;
esac
