#!/bin/bash

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

PARAMS=( "$@" )
UPDATE_SERVER="update.2x.mikbill.pro"

while [[ $# -gt 0 ]]; do
  key="$1"

  case $key in
    -t|--testing)
      # shellcheck disable=SC2034
      TYPE="current"
	  shift
      ;;
    -c|--current)
      # shellcheck disable=SC2034
      TYPE="current"
	  shift
      ;;
    -u|--update)
      TYPE="update"
	  shift
      ;;
    *)
      # unknown option
	  shift
      ;;
  esac
done

UPDATER_NAME="docker_admin_backed_updater"
UPDATER_REVISION=2
UPDATER_PATH="/var/mikbill/updates/update.sh"

FILE_NAME="mbadmin"
DOWNLOAD_DIR="/tmp"
WWW_DIR="/var/www/mikbill"
LOG_PATH="/var/log/mikbill_update.log"

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

URL="http://free.${TYPE}.2x.mikbill.pro"
if [ "$(ls -A "${LICENSE_DIR}")" ]; then
  URL="http://pay.${TYPE}.2x.mikbill.pro"
fi

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

if [ ! -d "${WWW_DIR}/admin" ]; then
	log "admin dir not found, skipping"
	return 0
fi

function log() {
	LOG_MESSAGE=$1
	echo "${LOG_MESSAGE}"

	LOG_DATE=$(date "+%F %H:%M:%S")
	echo "${LOG_DATE} ${LOG_MESSAGE}" >> "${LOG_PATH}"
}

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/Connection/Updates expired"
        return 1
    fi

    return 0
}

function clear_backup_dir() {
    if [ -d $BACKUP_DIR ]; then
        find $BACKUP_DIR/ -mtime +7 -type f |sort|xargs rm -f
    fi
}

function update_updater() {
  cd "${DOWNLOAD_DIR}" || exit
  log "check new version for UPDATER"
  SITE_REVISION=$(wget -qO- "${URL}/${UPDATER_NAME}.revision")
  if [ -n "${SITE_REVISION}" ]; then
    if [ "${SITE_REVISION}" != "${UPDATER_REVISION}" ]; then
      log "found new version for UPDATER"
      download_file "${URL}/${UPDATER_NAME}.sh" "${DOWNLOAD_DIR}/${UPDATER_NAME}.new"
      if [ $? -ne 0 ]; then
        log "download FAILED! please check DNS/Connection/Updates expired"
        if [ -f "${DOWNLOAD_DIR}/${UPDATER_NAME}.new" ]; then
          rm -f "${DOWNLOAD_DIR}/${UPDATER_NAME}.new"
        fi
        exit 0
      fi

      log "run NEW VERSION UPDATER"
      if [ -f "${UPDATER_PATH}" ]; then
        rm -f "${UPDATER_PATH}"
      fi

      mv "${DOWNLOAD_DIR}/${UPDATER_NAME}.new" "${UPDATER_PATH}"
      chmod +x "${UPDATER_PATH}"
      bash "${UPDATER_PATH} --${TYPE}"
      exit 0
    else
      log "installed latest version UPDATER"
    fi
  fi
}

function update_files() {
  DATENAME=$(date +%F_%H)

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

	log "create backup to ${BACKUP_DIR}/${FILE_NAME}.${DATENAME}.tar.gz"
	if [ -f "${BACKUP_DIR}/${FILE_NAME}.${DATENAME}.tar.gz" ]; then
		rm -f "${BACKUP_DIR}/${FILE_NAME}.${DATENAME}.tar.gz"
	fi

	cd $WWW_DIR
	tar -zcf "${FILE_NAME}.${DATENAME}.tar.gz" \
			--exclude="admin/sys"\
			--exclude="admin/app/log"\
			--exclude="admin/res"\
			--exclude="admin/MBPlatform"\
			--exclude="admin/classic*"\
			--exclude="admin/modern*"\
			--exclude="admin/index.html"\
			admin/

	mv "{$FILE_NAME}.{$DATENAME}.tar.gz" "${BACKUP_DIR}/"

	log "install new ${TYPE} ${FILE_NAME} update"

	cd "${DOWNLOAD_DIR}" || exit
	tar -zxf "${FILE_NAME}.tar.gz"
	/bin/mv -f "index.php" "${WWW_DIR}/admin/index.php"

	cd "${WWW_DIR}" || exit
	log || php "index.php" "sql_upd"

	log "done"
}

update_updater
update_files
clear_backup_dir
