#!/bin/bash

URL="http://free.update.lkv2.mikbill.pro"
#URL="http://pay.update.lkv2.mikbill.pro"

FILE_NAME="stat"
UPDATE_NAME="mbstat_update"

WWW_DIR="{{ mbstat.dirs.production }}/public"
UPD_DIR="{{ billing.dirs.updates }}/mbstat"
BKP_DIR="{{ billing.dirs.backup }}/mbstat"
TMP_DIR="/tmp"

DATENAME=$(date +%F_%H-%M)

if [ ! -d "$WWW_DIR" ]; then
	echo "mbstat dir not found"
	exit 0
fi

if [ ! -d $BKP_DIR ]; then
	mkdir -p $BKP_DIR
fi

cd $UPD_DIR
# check updater version
if [ ! -f $UPDATE_NAME.current.checksum ]; then
	echo 0 > $UPDATE_NAME.current.checksum
fi

wget -O $UPDATE_NAME.downloaded.checksum -q $URL/$UPDATE_NAME.checksum
if [ $? -ne 0 ]; then
	echo "Download FAILED! please check DNS and connection to $URL/$UPDATE_NAME.checksum"
	if [ -f $$UPDATE_NAME.downloaded.checksum ]; then
		rm -f $$UPDATE_NAME.downloaded.checksum
	fi
	exit 0
fi
MD5_CURRENT=$(cat $UPDATE_NAME.current.checksum)
MD5_DOWNLOADED=$(cat $UPDATE_NAME.downloaded.checksum)
if [ "$MD5_CURRENT" != "$MD5_DOWNLOADED" ]; then
	echo "download new updater version!"
	wget -q -O $TMP_DIR/$UPDATE_NAME.sh $URL/$UPDATE_NAME.sh
	if [ $? -ne 0 ]; then
		echo "Download FAILED! please check DNS and connection to $URL/$UPDATE_NAME.sh"
		rm -f $TMP_DIR/$UPDATE_NAME.sh
		exit 0
	fi

	if [ -f $TMP_DIR/$UPDATE_NAME.sh ]; then
		echo "$MD5_DOWNLOADED" > $UPD_DIR/$UPDATE_NAME.current.checksum
		
		rm -f $UPD_DIR/$UPDATE_NAME.sh
		mv $TMP_DIR/$UPDATE_NAME.sh $UPD_DIR/$UPDATE_NAME.sh
		chmod a+x $UPD_DIR/$UPDATE_NAME.sh
		echo "RUN new version UPDATER SOFT!"

		./$UPDATE_NAME.sh
		echo "Update of UPDATER SOFT Success!"
	fi

	exit
fi

# check update version
wget -O $FILE_NAME.downloaded.checksum -q $URL/$FILE_NAME.checksum
if [ $? -ne 0 ]; then
	echo "Download FAILED! please check DNS and connection to $URL/$FILE_NAME.checksum"
	if [ -f $FILE_NAME.downloaded.checksum ]; then
		rm -f $FILE_NAME.downloaded.checksum
	fi
	exit 0
fi

if [ ! -f $FILE_NAME.current.checksum ]; then
	echo 0 > $FILE_NAME.current.checksum
fi

MD5_CURRENT=$(cat $FILE_NAME.current.checksum)
MD5_DOWNLOADED=$(cat $FILE_NAME.downloaded.checksum)
if [ "$MD5_CURRENT" != "$MD5_DOWNLOADED" ]; then
	echo "download mbstat update..."
	cd $TMP_DIR
	wget -O $FILE_NAME.tar.gz -q $URL/$FILE_NAME.tar.gz
	if [ $? -ne 0 ]; then
        echo "Download FAILED! please check DNS and connection to $URL/$FILE_NAME"
		if [ -f $FILE_NAME.tar.gz ]; then
			rm -f $FILE_NAME.tar.gz
		fi 
        exit 0
	fi
	echo "$MD5_DOWNLOADED" > $UPD_DIR/$FILE_NAME.current.checksum

	if [ -d $WWW_DIR ]; then
		if [ -d $BKP_DIR ]; then
			echo "backup current version to $BKP_DIR/mbstat.$DATENAME.tar.gz"
			tar -zcf mbstat.$DATENAME.tar.gz --exclude='stat/sys' $WWW_DIR
			mv mbstat.$DATENAME.tar.gz $BKP_DIR/
		fi

		echo "install new stat update"
		tar -zxf $FILE_NAME.tar.gz --strip-components=2 -C $WWW_DIR
		rm -f $FILE_NAME.tar.gz
	else
		echo "$WWW_DIR not found! check path"
	fi
else
	echo "installed latest stat"
fi
