#!/bin/bash

if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root"
   exit 1
fi

VERSION_UPD="46"
ARG1=$1

LICENSE_DIR="/var/mikbill/license"
if [ ! -d "${LICENSE_DIR}" ]; then
  mkdir -p "${LICENSE_DIR}"
fi

MIKBILL_ETC="/var/www/mikbill/admin/app/etc"
MIKBILL_SOFT_VERSION="free"
if [ "$(ls -A "${LICENSE_DIR}")" ]; then
  MIKBILL_SOFT_VERSION="pay"
else
  if [ -d "${MIKBILL_ETC}" ]; then
    if [ -f "${MIKBILL_ETC}/serv.crt" ] && [ -f "${MIKBILL_ETC}/client.key" ]; then
      MIKBILL_SOFT_VERSION="pay"
    fi
  fi
fi

echo "Start ${MIKBILL_SOFT_VERSION} version of UPDATER SOFT!"

UPDATE_URL="http://${MIKBILL_SOFT_VERSION}.update.2x.mikbill.pro/"
UPDATE_FILE="mikbill.tar.gz"
UPDATE_FILE_CHECKSUM="mikbill_checksum"
UPDATE_VERSION_UPDATER="mikbill_rev_up"
UPDATE_VERSION_MIKBILL="mikbill_revision"
UPDATE_VERSION_MIKBILL_CURRENT="mikbill_current"
MIKBILL_CONTACT_MESSAGE="У вас закончились обновления вопросы на sales@mikbill.pro"
MIKBILL_PATH_LINUX="/var/www/mikbill"
MIKBILL_PATH_BSD="/usr/local/www/mikbill"
MIKBILL_PATH_LINUX_INST="/var/www"
MIKBILL_PATH_BSD_INST="/usr/local/www"
MIKBILL_LOG_UPDATE="mikbill_update.log"
MIKBILL_UPDATE_PROGRAMM="mikbill_update.sh"
MIKBILL_CURRENT_FILE_CHECKSUM="mikbill_checksum_current"
MIKBILL_DEF_PORT="22007"

TEST="0"

UNAME=`which uname`
ARCH=`$UNAME -m`
SYSTEM=`$UNAME`
NULL=" >/dev/null"

APP_ECHO=`which echo`
APP_WGET=`which wget`
APP_GREP=`which grep`
APP_AWK=`which awk`
APP_CAT=`which cat`
APP_RM=`which rm`
APP_PHP=`which php`
APP_LSB_RELEASE="111"
APP_SED=`which sed`
APP_CHMOD=`which chmod`
APP_CHOWN=`which chown`
APP_TAR=`which tar`
APP_DATE=`which date`
APP_CP=`which cp`
APP_SERVICE=`which service`
APP_SYSTEMCTL=`which systemctl`

SESS_PATH=$(php -i | grep session.save_path | awk '{ print $3 }')
if [[ $SESS_PATH == *"php"* ]]; then
  chmod 777 $SESS_PATH
fi

xml_config="/var/www/mikbill/admin/app/etc/config.xml"
if [[ -f $xml_config ]]; then
	MIKBILL_DEF_PORT=$(grep -oPm1 "(?<=<port>)[^<]+" $xml_config)
fi

function change_mbsql_upd() {
  if [ -f "/var/www/mikbill/admin/sys/update/mb_sql_upd.sh" ]; then
    if [ -f "/var/mikbill/prod/config/admin.xml" ]; then
      sed -i "s|../../app/etc/config.xml|/var/mikbill/prod/config/admin.xml|g" "/var/www/mikbill/admin/sys/update/mb_sql_upd.sh"
    fi
  fi
}

check_php_version () {
	#Проверить версию PHP и изменить ссылку для загрузки
	#подразумевается что уже система нормально установлена

	case $SYSTEM in
	Linux)
		PHPVER=`$APP_PHP -i|$APP_GREP PHP |$APP_GREP Version |$APP_AWK {'print $4'}|$APP_SED 's/\./ /g' |$APP_SED -n 1p |$APP_AWK {'print $2'}`
		;;
	FreeBSD)
		PHPVER=`$APP_PHP -i|$APP_GREP PHP |$APP_GREP Version |$APP_AWK '{print $4}'|$APP_SED 's/\./ /g' |$APP_SED -n 1p |$APP_AWK '{print $2}'`
		;;
	esac
}

control_version_updater () {
	#Выполняем проверку и контроль версии программы обновлений

	$APP_WGET -q  $UPDATE_URL$UPDATE_VERSION_UPDATER $NULL
	if [ ! -f ./$UPDATE_VERSION_UPDATER ] ; then
		echo "Connection error file $UPDATE_VERSION_UPDATER"
		exit
	fi

	VERSION_UPDATER=`$APP_CAT ./$UPDATE_VERSION_UPDATER`

	if [ $VERSION_UPDATER -ne $VERSION_UPD ] ; then
		echo "Detect Update of UPDATER SOFT!"
		$APP_RM -f ./$MIKBILL_UPDATE_PROGRAMM $NULL
		$APP_WGET -q $UPDATE_URL$MIKBILL_UPDATE_PROGRAMM $NULL
		$APP_CHMOD a+x ./$MIKBILL_UPDATE_PROGRAMM
		echo "RUN new version UPDATER SOFT!"

		./$MIKBILL_UPDATE_PROGRAMM
		echo "Update of UPDATER SOFT Success!"
		exit
	fi

	echo "NO Update detected for UPDATER SOFT"
}

control_version_mikbill () {
	#Проверка версии MikBill
	$APP_RM -f ./$UPDATE_VERSION_MIKBILL $NULL
	$APP_WGET -q $UPDATE_URL$UPDATE_VERSION_MIKBILL $NULL

	if [ ! -f ./$UPDATE_VERSION_MIKBILL ] ; then
		echo "Connection error file $UPDATE_VERSION_MIKBILL"
		exit
	fi

	VERSION_MIKBILL=`$APP_CAT ./$UPDATE_VERSION_MIKBILL`
	VERSION_MIKBILL_CURRENT=`$APP_CAT ./$UPDATE_VERSION_MIKBILL_CURRENT`


	if [ "$ARG1" != "" ] ; then
		exit
	fi

	if [ -f ./$UPDATE_VERSION_MIKBILL_CURRENT ] ; then
		if [ -f ./$MIKBILL_CURRENT_FILE_CHECKSUM ] ; then
			#вначала проверка на версию
			if [ $VERSION_MIKBILL -eq $VERSION_MIKBILL_CURRENT ]; then
				#загрузка контрольной суммы скачаного обновления
				$APP_WGET -q $UPDATE_URL$UPDATE_FILE_CHECKSUM $NULL
				if [ ! -f ./$UPDATE_FILE_CHECKSUM ] ; then
					echo "Connection error file $UPDATE_FILE_CHECKSUM"
					exit
				fi

				FILE_CHECKSUM=`$APP_CAT ./$UPDATE_FILE_CHECKSUM`
				FILE_CHECKSUM_CURRENT=`$APP_CAT ./$MIKBILL_CURRENT_FILE_CHECKSUM`
				#Проверка текущей мд5 и мд5 на сервере
				if [ "$FILE_CHECKSUM_CURRENT" != "$FILE_CHECKSUM" ] ; then
					#мд5 изменился требуется скачать обновление
					echo "Do reload Version MIkBiLL"
				else
					#мд5 равны, обновление не требуется
					delete_downloaded_files
					echo "MikBiLl Version is UP to Date"
					exit
				fi
			else
				echo "Have New Version MIkBiLL"
			fi
		else
			#Нет файла - нужно переобновить обязательно
			echo "Do reload Version MIkBiLL"
		fi
	else
		$APP_CAT ./$UPDATE_VERSION_MIKBILL > ./$UPDATE_VERSION_MIKBILL_CURRENT
		echo "Version file not found"
		echo "Do current version file"
	fi
}

control_cheksum_mikbill () {
	#Проверка контрольной суммы скачаного обновления
	$APP_WGET -q $UPDATE_URL$UPDATE_FILE_CHECKSUM $NULL
	if [ ! -f ./$UPDATE_FILE_CHECKSUM ] ; then
		echo "Connection error file $UPDATE_FILE_CHECKSUM"
		exit
	fi

	FILE_CHECKSUM=`$APP_CAT ./$UPDATE_FILE_CHECKSUM`
	$APP_WGET -q $UPDATE_URL$UPDATE_FILE $NULL
	if [ ! -f ./$UPDATE_FILE ] ; then
		echo "Connection error file $UPDATE_FILE"
		exit
	fi


	case $SYSTEM in
		Linux)
			APP_MD5=`which md5sum`
			DOWNLOAD_CHECKSUM=`$APP_MD5 ./$UPDATE_FILE|$APP_AWK {'print $1'}`
		;;
		FreeBSD)
			APP_MD5=`which md5`
			DOWNLOAD_CHECKSUM=`$APP_MD5 ./$UPDATE_FILE|$APP_AWK '{print $4}'`
		;;
	esac

	if [ "$DOWNLOAD_CHECKSUM" != "$FILE_CHECKSUM" ] ; then
		echo "Update file Checksumm error $MIKBILL_CONTACT_MESSAGE "
		exit
	fi
	#сохраним текущий мд5
	echo $FILE_CHECKSUM > ./$MIKBILL_CURRENT_FILE_CHECKSUM
	echo "Checksumm is OK!"
}

delete_downloaded_files () {
	#Удаляет загружаемые файлы

	$APP_RM -f ./$UPDATE_FILE $NULL
	$APP_RM -f ./$UPDATE_FILE_CHECKSUM $NULL
	$APP_RM -f ./$UPDATE_VERSION_UPDATER $NULL

	$APP_RM -f ./mikbill.tar.gz.*
	$APP_RM -f ./mikbill_checksum.*
	$APP_RM -f ./mikbill_rev_up.*
	$APP_RM -f ./mikbill_revision.*
	$APP_RM -f ./mikbill_update.sh.*
	$APP_RM -f ./index.php*

	echo "Delete downloaded old files success!"
}

detect_linux () {
	#Действия после определения Linux системы
	APP_NETSTAT=`which netstat`
	echo "Detect Linux System $ARCH"
	if [ -d $MIKBILL_PATH_LINUX ] ; then
		echo "MikBIll Path=$MIKBILL_PATH_LINUX"
	else
		echo "Error MikBill Dir Not Found"
		TEST="1"
	fi
}

detect_freebsd () {
	#Действия после определения FreeBSD системы
	APP_SOCKSTAT=`which sockstat`
	echo "Detect FreeBSD System $ARCH"
	if [ -d $MIKBILL_PATH_BSD ] ; then
		echo "MikBIll Path=$MIKBILL_PATH_BSD"
	else
		echo "Error MikBill Dir Not Found"
		TEST="1"
	fi
}

do_actions_centos () {
	#Делать действия для CentOS
	if [ "$TEST" == "0" ] ; then
		$APP_TAR xzf ./$UPDATE_FILE -C $MIKBILL_PATH_LINUX_INST
		$APP_CHOWN -R apache:apache $MIKBILL_PATH_LINUX
		do_rhel_reload
	fi
	IS_CENTOS_6=`$APP_CAT /etc/redhat-release|$APP_GREP 6.`
	if [ "$IS_CENTOS_6" == "" ] ; then
		echo "Detect CenteOS 5.x $ARCH";
	else
		echo "Detect CentOS 6.x $ARCH";
	fi
}

do_actions_gentoo () {
	#Делать действия для Gentoo
	echo "Detect Gentoo"
	if [ "$TEST" == "0" ] ; then
		$APP_TAR xzf ./$UPDATE_FILE -C $MIKBILL_PATH_LINUX_INST
		$APP_CHOWN -R apache:apache $MIKBILL_PATH_LINUX
		do_rhel_reload
	fi
}

do_actions_ubuntu () {
	#Делать действия для Ubuntu
	echo "Detect $DISTRIBUTOR $VERSION_UBUNTU $ARCH"
	if [ "$TEST" == "0" ] ; then
		$APP_TAR xzf ./$UPDATE_FILE -C $MIKBILL_PATH_LINUX_INST
		$APP_CHOWN -R www-data:www-data $MIKBILL_PATH_LINUX
		do_debian_reload
	fi
}

do_actions_debian () {
	#Делать действия для Debian
	echo "Detect $DISTRIBUTOR $VERSION_UBUNTU $ARCH"
	if [ "$TEST" == "0" ] ; then
		$APP_TAR xzf ./$UPDATE_FILE -C $MIKBILL_PATH_LINUX_INST
		$APP_CHOWN -R www-data:www-data $MIKBILL_PATH_LINUX
		do_debian_reload
	fi
}

do_actions_freebsd () {
	#Делать действия для FreeBSD
	if [ "$TEST" == "0" ] ; then
		$APP_TAR xzf ./$UPDATE_FILE -C $MIKBILL_PATH_BSD_INST
		$APP_CHOWN -R www:www $MIKBILL_PATH_BSD
		do_bsd_reload
	fi
}

check_gentoo () {
	#проверка на Gentoo
	if [ -f /etc/gentoo-release ] ; then
		APP_LSB_RELEASE=""
	fi
}

check_centos () {
	#проверка на CentOS
	if [ -f /etc/redhat-release ] ; then
		APP_LSB_RELEASE=""
	fi
}

do_final_actions () {
	#Выполнить финальные действия
	if [ "$TEST" == "0" ] ; then
	  if [ -f "${UPDATE_VERSION_MIKBILL}" ]; then
		  $APP_CAT ./$UPDATE_VERSION_MIKBILL > ./$UPDATE_VERSION_MIKBILL_CURRENT
		  echo "Update Success!"
		fi
	else
		echo "Update Error $MIKBILL_CONTACT_MESSAGE"
	fi
	delete_downloaded_files
}

do_final_unknown_linux () {
	#Финал для неизвестной OS
    delete_downloaded_files
    exit
}

do_rhel_reload () {
	cd $MIKBILL_PATH_LINUX"/admin/sys/update"
	echo "try change mbsql_upd path"
	change_mbsql_upd
	./mb_sql_upd.sh >> ./mikbill_update.log

        #Перезагрузка сервисов rhel like systems
        if [ ! -z "$APP_SYSTEMCTL" ]; then

                $APP_NETSTAT -nlp|$APP_GREP 181[2-3]
                $APP_SYSTEMCTL stop radiusd
                sleep 1

                $APP_NETSTAT -nlp|$APP_GREP "$MIKBILL_DEF_PORT"
                $APP_SYSTEMCTL stop mikbill
                sleep 1

               	$APP_SYSTEMCTL start mikbill
                $APP_NETSTAT -nlp|$APP_GREP "$MIKBILL_DEF_PORT"

               	$APP_SYSTEMCTL start radiusd
                sleep 1
               	$APP_NETSTAT -nlp|$APP_GREP 181[2-3]
        fi

        if [ ! -z "$APP_SERVICE" ]; then

                $APP_NETSTAT -nlp|$APP_GREP 181[2-3]
                $APP_SERVICE radiusd stop
                sleep 1

                $APP_NETSTAT -nlp|$APP_GREP "$MIKBILL_DEF_PORT"
                $APP_SERVICE mikbill stop
               	sleep 1

                $APP_SERVICE mikbill start
               	$APP_NETSTAT -nlp|$APP_GREP "$MIKBILL_DEF_PORT"

               	$APP_SERVICE radiusd start
                sleep 1
                $APP_NETSTAT -nlp|$APP_GREP 181[2-3]
        fi
}

do_debian_reload () {
	cd $MIKBILL_PATH_LINUX"/admin/sys/update"
	#change_mbsql_upd
	./mb_sql_upd.sh >> ./mikbill_update.log

        #Перезагрузка сервисов
        if [ ! -z "$APP_SYSTEMCTL" ]; then

                $APP_NETSTAT -nlp|$APP_GREP 181[2-3]
                $APP_SYSTEMCTL stop freeradius
                sleep 1

                $APP_NETSTAT -nlp|$APP_GREP "$MIKBILL_DEF_PORT"
                $APP_SYSTEMCTL stop mikbill
                sleep 1

               	$APP_SYSTEMCTL start mikbill
                $APP_NETSTAT -nlp|$APP_GREP "$MIKBILL_DEF_PORT"

               	$APP_SYSTEMCTL start freeradius
                sleep 1
               	$APP_NETSTAT -nlp|$APP_GREP 181[2-3]
        fi

        if [ ! -z "$APP_SERVICE" ]; then

                $APP_NETSTAT -nlp|$APP_GREP 181[2-3]
                $APP_SERVICE freeradius stop
                sleep 1

                $APP_NETSTAT -nlp|$APP_GREP "$MIKBILL_DEF_PORT"
                $APP_SERVICE mikbill stop
               	sleep 1

                $APP_SERVICE mikbill start
               	$APP_NETSTAT -nlp|$APP_GREP "$MIKBILL_DEF_PORT"

               	$APP_SERVICE freeradius start
                sleep 1
                $APP_NETSTAT -nlp|$APP_GREP 181[2-3]
        fi
}

do_stat () {
    # stat
    STAT_UPD_URL="http://${MIKBILL_SOFT_VERSION}.update.lkv2.mikbill.pro/stat_update.sh"
    STAT_UPD_DIR="/var/mikbill/updates/stat"
    STAT_UPD_FILE="stat_update.sh"

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

    if [ ! -f "$STAT_UPD_DIR/autoupdate" ]; then
       	echo 1 > $STAT_UPD_DIR/autoupdate
    fi

    STAT_UPDATE_ENABLED=$(cat $STAT_UPD_DIR/autoupdate)
    if [ "$STAT_UPDATE_ENABLED" == "1" ]; then
        if [ -f "$STAT_UPD_DIR/$STAT_UPD_FILE" ]; then
                rm -f $STAT_UPD_DIR/$STAT_UPD_FILE
       	fi

        if [ ! -f "$STAT_UPD_DIR/$STAT_UPD_FILE" ]; then
               	wget -O $STAT_UPD_FILE -q $STAT_UPD_URL
                if [ $? -ne 0 ]; then
                        echo "Download  FAILED! please check DNS and connection to $STAT_UPD_URL"
                        exit 0
                fi
               	chmod +x $STAT_UPD_FILE
                mv $STAT_UPD_FILE $STAT_UPD_DIR
       	fi
        CUR_DIR=$(pwd)
       	/bin/bash $STAT_UPD_DIR/$STAT_UPD_FILE
        cd $CUR_DIR
    fi
}

do_mbplatform () {
    # mbdash
    MBDASH_DIR="/var/mikbill/updates/mbplatform"
    MBDASH_UPD_URL="http://${MIKBILL_SOFT_VERSION}.update.2x.mikbill.pro/mbplatform_updater.sh"
    if [ ! -d $MBDASH_DIR ]; then
		mkdir -p $MBDASH_DIR
    fi

    if [ ! -f $MBDASH_DIR/autoupdate ]; then
		echo 1 > $MBDASH_DIR/autoupdate
    fi

    MBDASH_UPDATE_ENABLED=$(cat $MBDASH_DIR/autoupdate)
    if [ "$MBDASH_UPDATE_ENABLED" = "1" ]; then
		if [ -f $MBDASH_DIR/mbplatform_updater.sh ]; then
			rm -f $MBDASH_DIR/mbplatform_updater.sh
		fi

		if [ ! -f $MBDASH_DIR/mbplatform_updater.sh ]; then
			wget -O mbplatform_updater.sh -q $MBDASH_UPD_URL
			if [ $? -ne 0 ]; then
				echo "Download  FAILED! please check DNS and connection to ${MBDASH_UPD_URL}"
				exit 0
			fi
			chmod +x mbplatform_updater.sh
			mv mbplatform_updater.sh $MBDASH_DIR
		fi
		CUR_DIR=$(pwd)
		/bin/bash $MBDASH_DIR/mbplatform_updater.sh
		cd $CUR_DIR
    fi
}

do_prerelease () {
        # pre-release updates
        PRE_DIR="/var/mikbill/updates/pre_release"
        PRE_UPD_URL="http://${MIKBILL_SOFT_VERSION}.current.2x.mikbill.pro"
        if [ ! -d $PRE_DIR ]; then
                mkdir -p $PRE_DIR
        fi

        FNAME="install_pre-release.sh"
        if [ ! -f $PRE_DIR/$FNAME ]; then
                wget -O $FNAME -q $PRE_UPD_URL/$FNAME
                chmod +x $FNAME
                # ставим новый
                mv $FNAME $PRE_DIR
       	else
                wget -O $FNAME -q $PRE_UPD_URL/$FNAME
                chmod +x $FNAME
                # удаляем старый
                rm -f $PRE_DIR/$FNAME
                # ставим новый
                mv $FNAME $PRE_DIR
       	fi

        FNAME="undo_pre-release.sh"
        if [ ! -f $PRE_DIR/$FNAME ]; then
                wget -O $FNAME -q $PRE_UPD_URL/$FNAME
                chmod +x $FNAME
                # ставим новый
                mv $FNAME $PRE_DIR
       	else
                wget -O $FNAME -q $PRE_UPD_URL/$FNAME
                chmod +x $FNAME
                # удаляем старый
                rm -f $PRE_DIR/$FNAME
                # ставим новый
                mv $FNAME $PRE_DIR
       	fi
}

fix_radius_dict_premission() {
	path_radius=(
	"/etc/raddb"
	"/etc/freeradius"
	"/etc/freeradius/3.0"
	"/usr/local/etc/raddb"
	)

	for path_r in ${path_radius[*]}
	do
		if [ -d "$path_r" ]; then
			if [ -f "$path_r/dictionary" ]; then
				#echo "chmod 755 on $path_r/dictionary"
				chmod 755 "$path_r/dictionary"
			fi
		fi
	done

	ATT_LIST=(
	'ATTRIBUTE DHCP-Router-IP-Address 241 ipaddr'
	'ATTRIBUTE DHCP-Mask 242 integer'
	'ATTRIBUTE L4-Redirect 243 integer'
	'ATTRIBUTE L4-Redirect-ipset 244 string'
	'ATTRIBUTE DHCP-Option82 245 octets'
	'ATTRIBUTE AccelRemoteId 246 octets'
	'ATTRIBUTE AccelCircuitId 247 octets'
	)

	ETC_DICT="/etc/raddb/dictionary"
	if [ -f "/etc/freeradius/dictionary" ]; then
		ETC_DICT="/etc/freeradius/dictionary"
	fi

	if [ -f $ETC_DICT ]; then
		RAD_DICT=$(head -n 1 $ETC_DICT | awk '{print $2}')

		for ((i=0; i < ${#ATT_LIST[@]}; i++))
		do
			RAD_ATT="${ATT_LIST[$i]}"
			if grep -q "$RAD_ATT" $ETC_DICT; then
				sed -i "/$RAD_ATT/d" $ETC_DICT
				if ! grep -q "$RAD_ATT" $RAD_DICT; then
					echo "$RAD_ATT" >> $RAD_DICT
				fi
			fi
		done
	fi
}

fix_web_permissions() {
	files_owner="nginx"
	web_owner="apache"
	if command -v apt-get >/dev/null 2>&1; then
		web_owner="www-data"
	fi

	if [ -z "$(getent passwd $web_owner)" ]; then
		echo "create system user $web_owner"
		useradd -r "$web_owner"
	fi

	if [ -z "$(getent passwd $files_owner)" ]; then
		echo "create system user $files_owner"
		useradd -r "$files_owner"
	fi

	mikbill_path="/var/www/mikbill"
	if [[ -d /var/mikbill ]]; then
		chown $files_owner:$files_owner -R /var/mikbill
		find /var/mikbill -type f -iname "*.log" -exec chmod 666 {} \;
		find /var/mikbill -type f -iname "*.txt" -exec chmod 666 {} \;
		find /var/mikbill -type f -iname "*.sh" -exec chmod 755 {} \;
	fi

	if [[ -d /var/log/mikbill ]]; then
		chown $web_owner:$web_owner -R /var/log/mikbill
	fi

	if [[ -d $mikbill_path ]]; then
		find "$mikbill_path" -type f -exec chmod 644 -- {} +
		find "$mikbill_path" -type d -exec chmod 755 -- {} +
		chown $files_owner:$files_owner -R $mikbill_path
		chmod +x "${mikbill_path}/admin/sys/update/mikbill_update.sh"
		chmod +x "${mikbill_path}/admin/sys/update/mb_sql_upd.sh"
		if [ -d "${mikbill_path}/admin/app/log" ]; then
		  find "${mikbill_path}/admin/app/log" -type f -iname "*.log" -exec chmod 666 {} \;
		fi
    if [ -d "${mikbill_path}/stat/app/log" ]; then
      find "${mikbill_path}/stat/app/log" -type f -iname "*.txt" -exec chmod 666 {} \;
    fi
		if [ -d "${mikbill_path}/admin/sys/scripts" ]; then
		  find "${mikbill_path}/admin/sys/scripts" -type f -iname "*.sh" -exec chmod 755 {} \;
		fi
	fi
}

do_www_backup() {
	WORK_DIR="/var/www/mikbill"
	BACKUP_DIR="/var/mikbill/www_backups"

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

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

		cd $WORK_DIR
		if [ -d "$WORK_DIR/admin" ]; then
			tar -zcf admin.$DATENAME.tar.gz --exclude='admin/sys' --exclude='admin/res' --exclude='admin/MBPlatform' --exclude='admin/classic*' --exclude='admin/modern*' --exclude='admin/index.html'	admin/
			mv admin.$DATENAME.tar.gz $BACKUP_DIR/

			tar -zcf html5.$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 html5.$DATENAME.tar.gz $BACKUP_DIR/
		fi

		if [ -d "$WORK_DIR/stat" ]; then
			tar -zcf stat.$DATENAME.tar.gz --exclude='stat/sys' stat/
			mv stat.$DATENAME.tar.gz $BACKUP_DIR/
		fi

		find $BACKUP_DIR/ -mtime +7 -type f |sort|xargs rm -f

		cd $CUR_DIR
	fi
}

do_setup_lk_3x() {
	URL_LK="http://${MIKBILL_SOFT_VERSION}.update.lkv2.mikbill.pro"
	LK_NAME="stat"
	BACKUP_DIR="/var/mikbill/lk_2x_backup"
	BNAME="lk_v2_backup"

	CPcmd=$(which cp)

	if [ -d $BACKUP_DIR ]; then
		return 0
	fi

	CUR_DIR=$(pwd)
	cd ../../..
	WWW_DIR=$(pwd)

	# if current dir have stat folder
	if [ -d ./stat ]; then

		if [ ! -f ./stat/pay.php ]; then
			cd $CUR_DIR
			return 0
		fi

		if [ ! -d $BACKUP_DIR ]; then
			mkdir -p $BACKUP_DIR

			if [ ! -f $BACKUP_DIR/$BNAME.tar.gz ]; then
				tar czf $BNAME.tar.gz stat/
				mv $BNAME.tar.gz $BACKUP_DIR/

				rm -rf ./stat
				mkdir stat
			fi

			new_dirs=(
				"./stat/app/log"
				"./stat/app/etc"
				"./stat/res"
				"./stat/sys"
			)

			new_files=(
				"app/log/log.txt"
				"app/log/mbdebug.log"
				"app/log/requestfull.log"
			)

			for item in ${new_dirs[*]}
			do
				if [ ! -d $item ]; then
					mkdir -p $item
				fi
			done

			new_files=(
				"app/log/log.txt"
				"app/log/mbdebug.log"
				"app/log/requestfull.log"
			)

			for item in ${new_dirs[*]}
			do
				if [ ! -d $item ]; then
					mkdir -p $item
				fi
			done

			for item in ${new_files[*]}
			do
				if [ ! -f ./stat/$item ]; then
					touch ./stat/$item
				fi
			done

			cd $BACKUP_DIR
			if [ ! -d ./stat ]; then
				tar xzf $BNAME.tar.gz
			fi

			files_list=(
				"favicon.ico"
				"robots.txt"
				"app/etc/config.xml"
				"res/api_logo_1.jpg"
				"res/robokassa_logo.jpg"
			)

			dir_lists=(
				"data/template/olson/customtpls"
				"res/images"
				"res/locales"
				"res/logo"
			)

			for item in ${files_list[*]}
			do
				if [ -f ./stat/$item ]; then
					$CPcmd -f ./stat/$item $WWW_DIR/stat/$item
				fi
			done


			if [ -d ./stat/sys ]; then
				$CPcmd -Rf ./stat/sys $WWW_DIR/stat
			fi
		fi

		wget -O stat.downloaded.checksum -q $URL_LK/$LK_NAME.checksum
		if [ $? -ne 0 ]; then
			echo "Download  FAILED! please check DNS and connection to $URL_LK/stat.checksum"
			cd $CUR_DIR
			return 1
		fi

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

		MD5_CURRENT=$(cat stat.current.checksum)
		MD5_DOWNLOADED=$(cat stat.downloaded.checksum)
		if [ "$MD5_CURRENT" != "$MD5_DOWNLOADED" ]; then
			echo "download lkv3 update..."

			wget -O stat.tar.gz -q $URL_LK/$LK_NAME.tar.gz
			if [ $? -ne 0 ]; then
				echo "Download  FAILED! please check DNS and connection to $URL_LK/$LK_NAME.tar.gz"
				cd $CUR_DIR
				return 1
			fi
			echo "$MD5_DOWNLOADED" > stat.current.checksum

			if [ -f stat.tar.gz ]; then
					echo "install new lkv3 update"
					tar -zxf stat.tar.gz
					rm -f stat.tar.gz
			fi
		fi
	fi

	cd $CUR_DIR
}

phing_fix() {
	if [ -f "/usr/local/bin/phing" ]; then
    if [ ! -f "/usr/bin/phing" ]; then
      ln -s /usr/local/bin/phing /usr/bin/phing
    fi
  fi
}

function do_disable_function() {
  backup_name=$(date +%F_%H-%M)
  for php_ini_file in $(find /etc -type f -name "php.ini")
  do
    if [ -f "${php_ini_file}" ]; then
      echo "disable functions in ${php_ini_file}"
      chattr -i "${php_ini_file}"
      sed -e '/^[^;]*disable_functions/s/=.*$/= shell_exec,proc_terminate,pcntl_exec,passthru,proc_nice,dl,show_source,apache_note,apache_setenv,debugger_off,debugger_on,closelog,define_syslog_variables,ini_restore,openlog,syslog,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_uname,posix_setgid,posix_setuid,posix_setegid,posix_getpwuid,posix_setpgid,mail,apache_child_terminate,chgrp,chown,curl_multi_exec,define_syslog_variables,highlight_file,parse_ini_string,stream_select,imap_open,xmlrpc_entity_decode,inject_code,ini_alter,xmlrpc_encode,xmlrpc_decode,xmlrpc_get_type,xmlrpc_is_fault,xmlrpc_set_type,phpAds_remoteInfo,phpAds_XmlRpc,phpAds_xmlrpcDecode,phpAds_xmlrpcEncode,ftp_exec,ftp_get,ftp_nb_fput,ftp_raw,ftp_rawlist,symlink,assert,create_function,phpinfo,posix_ttyname,getenv,posix_getlogin,get_current_user,get_cfg_var,diskfreespace,getlastmo,getmygid,getmyinode,getmyuid,extract,putenv,pfsockopen,base64_decode,parse_ini_file,call_user_func_array,call_user_func/' -i ${php_ini_file}
      $APP_SERVICE php-fpm restart > /dev/null 2>&1
    fi
  done
}

function change_admin_log() {
	config="${MB_PATH_OLD}/admin/app/etc/config.xml"
	if [ -f "${config}" ]; then
		error_log_exists=$(grep -c "error_log" "${config}")
		debug_log_exists=$(grep -c "debug_log" "${config}")

		if [ "${error_log_exists}" == "0" ]; then
			error_log="        <error_log>${MB_PATH_LOG}/admin/general.log</error_log>"
			error=$(echo "${error_log}" | sed 's/\//\\\//g')
			sed -i "/<\/parameters>/ s/.*/${error}\n&/" "${config}"
			ADMIN_LOG_CHANGED=1

			if [ -f "${MB_PATH_OLD}/admin/app/log/log.txt" ]; then
				/bin/mv -f "${MB_PATH_OLD}/admin/app/log/log.txt" "${MB_PATH_LOG}/admin/general.log"
			fi
		fi

		if [ "${debug_log_exists}" == "0" ]; then
			debug_log="        <debug_log>${MB_PATH_LOG}/admin/debug.log</debug_log>"
			debug=$(echo "${debug_log}" | sed 's/\//\\\//g')
			sed -i "/<\/parameters>/ s/.*/${debug}\n&/" "${config}"
			ADMIN_LOG_CHANGED=1

			if [ -f "${MB_PATH_OLD}/admin/app/log/mbdebug.log" ]; then
				/bin/mv -f "${MB_PATH_OLD}/admin/app/log/mbdebug.log" "${MB_PATH_LOG}/admin/debug.log"
			fi
		fi
	fi
}

function change_stat_log() {
	config="${MB_PATH_OLD}/stat/app/etc/config.xml"
	if [ -f "${config}" ]; then
		error_log_exists=$(grep -c "error_log" "${config}")
		debug_log_exists=$(grep -c "debug_log" "${config}")

		if [ "${error_log_exists}" == "0" ]; then
			error_log="        <error_log>${MB_PATH_LOG}/stat/general.log</error_log>"
			error=$(echo "${error_log}" | sed 's/\//\\\//g')
			sed -i "/<\/parameters>/ s/.*/${error}\n&/" "${config}"
			STAT_LOG_CHANGED=1

			if [ -f "${MB_PATH_OLD}/stat/app/log/log.txt" ]; then
				/bin/mv -f "${MB_PATH_OLD}/stat/app/log/log.txt" "${MB_PATH_LOG}/stat/general.log"
			fi
		fi

		if [ "${debug_log_exists}" == "0" ]; then
			debug_log="        <debug_log>${MB_PATH_LOG}/stat/debug.log</debug_log>"
			debug=$(echo "${debug_log}" | sed 's/\//\\\//g')
			sed -i "/<\/parameters>/ s/.*/${debug}\n&/" "${config}"
			STAT_LOG_CHANGED=1

			if [ -f "${MB_PATH_OLD}/stat/app/log/mbdebug.log" ]; then
				/bin/mv -f "${MB_PATH_OLD}/stat/app/log/mbdebug.log" "${MB_PATH_LOG}/stat/debug.log"
			fi
		fi
	fi
}

function archive_admin_log_dir() {
	if [ ! -d "${MB_PATH_NEW}/old_files/admin/app" ]; then
		mkdir -p "${MB_PATH_NEW}/old_files/admin/app"
	fi

	if [ -f "${MB_PATH_LOG}/admin/general.log" ]; then
		if [ -d "${MB_PATH_OLD}/admin/app/log" ]; then
			/bin/mv -fu "${MB_PATH_OLD}/admin/app/log" "${MB_PATH_NEW}/old_files/admin/app"
		fi
	fi
}

function archive_stat_log_dir() {
	if [ ! -d "${MB_PATH_NEW}/old_files/stat/app" ]; then
		mkdir -p "${MB_PATH_NEW}/old_files/stat/app"
	fi

	if [ -f "${MB_PATH_LOG}/stat/general.log" ]; then
		if [ -d "${MB_PATH_OLD}/stat/app/log" ]; then
			/bin/mv -fu "${MB_PATH_OLD}/stat/app/log" "${MB_PATH_NEW}/old_files/stat/app"
		fi
	fi
}

function move_scripts_dir() {
	if [ ! -d "${MB_PATH_NEW}/scripts" ]; then
		/bin/mv -fu "${MB_PATH_OLD}/admin/sys/scripts" "${MB_PATH_NEW}/"
	fi
}

function move_mrtg_dir() {
	if [ ! -d "${MB_PATH_NEW}/mrtg" ]; then
		/bin/mv -fu "${MB_PATH_OLD}/admin/sys/mrtg" "${MB_PATH_NEW}/"
	fi
}

function move_mrtg_users_dir() {
	if [ ! -d "${MB_PATH_NEW}/mrtg_users" ]; then
		/bin/mv -fu "${MB_PATH_OLD}/admin/sys/mrtg_users" "${MB_PATH_NEW}/"
	fi
}

function config_mrtg_gen() {
  cd "${MB_PATH_OLD}/admin/" || return
	php index.php config_mrtg_gen
}

function move_admin_conf() {
	if [ -f "${MB_PATH_OLD}/admin/app/etc/config.xml" ]; then
		mv -f "${MB_PATH_OLD}/admin/app/etc/config.xml" "${MB_PATH_NEW}/config/admin.xml"
	fi
}

function move_stat_conf() {
	if [ -f "${MB_PATH_OLD}/stat/app/etc/config.xml" ]; then
		mv -f "${MB_PATH_OLD}/stat/app/etc/config.xml" "${MB_PATH_NEW}/config/stat.xml"
	fi
}

function move_mbp_conf() {
	if [ -f "${MB_PATH_OLD}/admin/app/etc/config.ini" ]; then
		mv -f "${MB_PATH_OLD}/admin/app/etc/config.ini" "${MB_PATH_NEW}/config/mbp.ini"
	fi
}

function change_admin_logrotate() {
  if [ -f /etc/logrotate.d/mikbill ]; then
    sed -i "s|${MB_PATH_OLD}/admin/app/log/log.txt|${MB_PATH_LOG}/admin/*.log|g" /etc/logrotate.d/mikbill
  fi
}

function change_stat_logrotate() {
  if [ -f /etc/logrotate.d/mikbill ]; then
    sed -i "s|${MB_PATH_OLD}/stat/app/log/log.txt|${MB_PATH_LOG}/stat/*.log|g" /etc/logrotate.d/mikbill
  fi
}

function change_cron() {
  cron_changed=0
  if [ -d "${MB_PATH_NEW}/scripts" ]; then
    if [ -f /etc/cron.d/mikbill ]; then
      scripts_count=$(grep -c "${MB_PATH_OLD}/admin/sys/scripts" /etc/cron.d/mikbill)
      if [ "${scripts_count}" != "0" ]; then
        sed -i "s|${MB_PATH_OLD}/admin/sys/scripts|${MB_PATH_NEW}/scripts|g" /etc/cron.d/mikbill
        cron_changed=1
      fi
    fi

    if [ -f /etc/crontab ]; then
      scripts_count=$(grep -c "${MB_PATH_OLD}/admin/sys/scripts" /etc/crontab)
      if [ "${scripts_count}" != "0" ]; then
        sed -i "s|${MB_PATH_OLD}/admin/sys/scripts|${MB_PATH_NEW}/scripts|g" /etc/crontab
        cron_changed=1
      fi
    fi

    if [ "${cron_changed}" == "1" ]; then
      service cron restart > /dev/null 2>&1
      service crond restart > /dev/null 2>&1
    fi
  fi
}

function change_sms() {
  if [ -f "${MB_PATH_NEW}/config/admin.xml" ]; then
    backup_name=$(date +%F_%H-%M)
    for sms_config_file in $(find /var/mikbill -type f -name "ConfigClass.php")
    do
      if [ -f "${sms_config_file}" ]; then
        xml_count=$(grep -c "${MB_PATH_OLD}/admin/app/etc/config.xml" "${sms_config_file}")
        if [ "${xml_count}" != "0" ]; then
          echo "change sms xml config path in ${sms_config_file}"
          sed "s|${MB_PATH_OLD}/admin/app/etc/config.xml|${MB_PATH_NEW}/config/admin.xml|g" -i.${backup_name} ${sms_config_file}
        fi
      fi
    done
  fi
}

function change_mysql_backup() {
  if [ -f "${MB_PATH_NEW}/config/admin.xml" ]; then
    backup_name=$(date +%F_%H-%M)
    for backup_file in $(find /var/mikbill -type f -name "mysql_backup.sh")
    do
      if [ -f "${backup_file}" ]; then
        xml_count=$(grep -c "admin/app/etc/config.xml" "${backup_file}")
        if [ "${xml_count}" != "0" ]; then
          echo "change mysql backup xml config path in ${backup_file}"
          sed "s|/var/www/mikbill|/var/mikbill/prod|g" -i ${backup_file}
          sed "s|admin/app/etc/config.xml|config/admin.xml|g" -i ${backup_file}
        fi
      fi
    done
  fi
}

do_restructure() {
  MB_PATH_OLD="/var/www/mikbill"
  MB_PATH_NEW="/var/mikbill/prod"
  MB_PATH_LOG="/var/log/mikbill"
  ADMIN_LOG_CHANGED=0
  STAT_LOG_CHANGED=0

  cd "${MB_PATH_OLD}/admin/" || return
  restructure=$(php index.php do_restructure)
  if [ $? -eq 0 ]; then
    if [ "${restructure}" == "1" ]; then

      if [ ! -d "${MB_PATH_LOG}/admin" ]; then
        mkdir -p "${MB_PATH_LOG}/admin"
      fi
      if [ ! -d "${MB_PATH_LOG}/stat" ]; then
			  mkdir -p "${MB_PATH_LOG}/stat"
		  fi
      if [ ! -d "${MB_PATH_NEW}/config" ]; then
        mkdir -p "${MB_PATH_NEW}/config"
      fi
      if [ ! -d "${MB_PATH_NEW}/old_files/admin/app" ]; then
        mkdir -p "${MB_PATH_NEW}/old_files/admin/app"
      fi
      if [ ! -d "${MB_PATH_NEW}/old_files/admin/res" ]; then
        mkdir -p "${MB_PATH_NEW}/old_files/admin/res"
      fi
      if [ ! -d "${MB_PATH_NEW}/old_files/admin/sys" ]; then
        mkdir -p "${MB_PATH_NEW}/old_files/admin/sys"
      fi

      change_admin_log
      change_stat_log

      if [ "${ADMIN_LOG_CHANGED}" == "1" ]; then
        archive_admin_log_dir
        change_admin_logrotate
      fi

      if [ "${STAT_LOG_CHANGED}" == "1" ]; then
        archive_stat_log_dir
        change_stat_logrotate
      fi

      move_scripts_dir
      move_mrtg_dir
      move_mrtg_users_dir
      config_mrtg_gen
      move_admin_conf
      move_stat_conf
      move_mbp_conf
      change_mbsql_upd
      change_cron
      change_sms
      change_mysql_backup
      do_disable_function
      fix_web_permissions
    fi
  fi
}

do_files_common() {
	fix_radius_dict_premission
	fix_web_permissions
	phing_fix
}

# delete old files
delete_downloaded_files

# check system php version
check_php_version
# fix files owner
fix_web_permissions

# save current dir
CURRENT_DIR=$(pwd)

# restructure
do_restructure
cd $CURRENT_DIR

# check updater version
control_version_updater
# check mikbill version
control_version_mikbill
# download mikbill
control_cheksum_mikbill

if [ -f ./$UPDATE_FILE ] ; then
    echo "Download Success!"

    # save current dir
    CURRENT_DIR=$(pwd)

    # save update dir
    UPD_INIT_DIR="$MIKBILL_PATH_LINUX/admin/sys/update"
    cd $UPD_INIT_DIR

    # make back + front backup
    do_www_backup
    cd $CURRENT_DIR

    case $SYSTEM in
    Linux)
        detect_linux
		check_gentoo
		check_centos

		if [ -z $APP_LSB_RELEASE ] ; then
			if [ -f /etc/gentoo-release ] ; then
				do_actions_gentoo
			else
				if [ -f /etc/redhat-release ] ; then
					do_actions_centos
				else
					echo "Uknown Linux"
					echo "Stop Update"
					TEST="1"
					do_final_unknown_linux
				fi
			fi
		else
			APP_LSB_RELEASE=`which lsb_release`
			DISTRIBUTOR=`$APP_LSB_RELEASE -a|$APP_GREP Distributor|$APP_AWK '{print $3}'`
			VERSION_UBUNTU=`$APP_LSB_RELEASE -a|$APP_GREP Release|$APP_AWK '{print $2}'`
			if [ "$DISTRIBUTOR" == "Ubuntu" ] ; then
				do_actions_ubuntu
			fi
			if [ "$DISTRIBUTOR" == "Debian" ] ; then
				do_actions_debian
			fi
		fi
    ;;
    FreeBSD)
        detect_freebsd
        do_actions_freebsd
    ;;
    esac

	# custom functions
	cd $UPD_INIT_DIR
	do_files_common

	cd $UPD_INIT_DIR
	# front
	do_mbplatform

	cd $UPD_INIT_DIR
	# remove old stat
	do_setup_lk_3x

	cd $UPD_INIT_DIR
	# stat front + back
	do_stat

	cd $UPD_INIT_DIR
	# dev updates
	do_prerelease

	cd $CURRENT_DIR
	# remove old files
	do_final_actions
else
    echo "Update Don't Download $MIKBILL_CONTACT_MESSAGE"
fi
