#!/bin/bash

FILE_NAME="MBDash-stable"
URL="http://update.mikbill.pro:9424/live/pay"

COMPONENT="html5"
DOWNLOAD_DIR="/tmp"
WWW_DIR="/var/www/mikbill"
BACKUP_DIR="/var/mikbill/www_backups"
HOME_DIR="/var/mikbill/updates/mbplatform"

CHKSUM_D="$COMPONENT.downloaded.checksum"
CHKSUM_C="$COMPONENT.current.checksum"

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

function download_file() {
    DOWNLOAD_URL=$1
    SAVE_FILENAME=$2

    if [ -f $SAVE_FILENAME ]; then
        rm -f $SAVE_FILENAME
    fi

    wget -O $SAVE_FILENAME -q --no-check-certificate $DOWNLOAD_URL
    if [ $? -ne 0 ]; then
        if [ -f $SAVE_FILENAME ]; then
            rm -f $SAVE_FILENAME
        fi

        echo "Download  FAILED! please check DNS and connection to $DOWNLOAD_URL"
        return 1
    fi

    return 0
}

cd $HOME_DIR
download_file $URL/$FILE_NAME.checksum $CHKSUM_D
if [ $? -ne 0 ]; then
    return 1
fi

if [ ! -f $CHKSUM_C ]; then
    echo 0 > $CHKSUM_C
fi

MD5_CURRENT=$(cat $CHKSUM_C)
MD5_DOWNLOADED=$(cat $CHKSUM_D)
if [ "$MD5_CURRENT" != "$MD5_DOWNLOADED" ]; then
    echo "download $COMPONENT release..."

    cd $DOWNLOAD_DIR
    download_file $URL/$FILE_NAME.tar.gz $FILE_NAME.tar.gz
    if [ $? -ne 0 ]; then
        exit 1
    fi

    echo "backup $COMPONENT to $BACKUP_DIR/$COMPONENT.$DATENAME.tar.gz"
    if [ ! -d $BACKUP_DIR ]; then
        mkdir -p $BACKUP_DIR
    fi

    if [ -f $BACKUP_DIR/$COMPONENT.$DATENAME.tar.gz ]; then
        rm -f $BACKUP_DIR/$COMPONENT.$DATENAME.tar.gz
    fi

    cd $WWW_DIR
    tar -zcf $COMPONENT.$DATENAME.tar.gz \
            --exclude="admin/sys"\
            --exclude="admin/res"\
            --exclude="admin/app"\
            --exclude="admin/mikbill.swf"\
            --exclude="admin/crossdomain.xml"\
            --exclude="admin/index.php"\
            admin/

    mv $COMPONENT.$DATENAME.tar.gz $BACKUP_DIR/

    echo "remove old $COMPONENT files"
    cd $WWW_DIR/admin/

    if [ -d MBPlatform ]; then
        rm -rf MBPlatform/
    fi

	if [ -f classic.json ]; then
        rm -f classic.json
    fi

	if [ -f classic.jsonp ]; then
        rm -f classic.jsonp
    fi

	if [ -f modern.json ]; then
        rm -f modern.json
    fi

	if [ -f modern.jsonp ]; then
        rm -f modern.jsonp
    fi

	if [ -f index.html ]; then
        rm -f index.html
    fi

    if [ -f $FILE_NAME.tar.gz ]; then
        rm -f $FILE_NAME.tar.gz
    fi

    echo "install new $COMPONENT update"
    mv $DOWNLOAD_DIR/$FILE_NAME.tar.gz ./
    tar -zxf $FILE_NAME.tar.gz
    rm -f $FILE_NAME.tar.gz

    echo "update md5 summ"
    cd $HOME_DIR
    echo "$MD5_DOWNLOADED" > $CHKSUM_C
    echo "done"

    if [ -f /tmp/html5.current.checksum  ]; then
	echo "remove pre-prelease checksum"
	rm -f /tmp/html5.current.checksum
    fi
    echo " "
else
    echo "installed latest $COMPONENT version"
    exit 0
fi
