#!/bin/bash
print_red () {
    echo -e "\033[91m"$1"\033[0m"
}
print_red_read () {
    echo -e -n "\033[91m"$1"\033[0m"
    read
}
print_yellow () {
    echo -e "\033[93m"$1"\033[0m"
}
print_yellow_read () {
    echo -e -n "\033[93m"$1"\033[0m"
    read
}
print_green () {
    echo -e "\033[92m"$1"\033[0m"
}
print_green_u () {
    echo -e "\033[92m\033[4m"$1"\033[0m"
}
get_license_key () {
    uri=$(grep uri /home/wnam/application.* | grep -v "#" | sed 's|.*.uri=||')
    if which mongo > /dev/null; then
        license_key=$(mongo --quiet $uri --eval "db.settings.find({'_id':'settingsid'},{'_id':0,'licenseKey':1})" | awk '{print $4}' | sed 's/"//g')
        if [ -z $license_key ]; then
            license_key=$(mongo --quiet $uri --eval "db.appSetting.find({_id: 'licenseKey'},{value:1})" | awk {'print $6'} | sed "s/'//g")
        fi
    elif which mongosh > /dev/null; then
        license_key=$(mongosh --quiet $uri --eval "db.settings.find({'_id':'settingsid'},{'_id':0,'licenseKey':1})" | awk '{print $4}' | sed 's/"//g')
        if [ -z $license_key ]; then
            license_key=$(mongosh --quiet $uri --eval "db.appSetting.find({_id: 'licenseKey'},{value:1})" | awk {'print $6'} | sed "s/'//g")
        fi
    fi
    if [ -z $license_key ]; then
        print_red "Лицензионный ключ не найден в БД"
        print_yellow_read "Введите лицензионный ключ, XXXX-XXXX-XXXX-XXXX: "
        license_key=$REPLY
    fi
}
validate_license_key () {
    get_license_key
    command='curl -s --request POST 'https://www.netams.com/cgi/download-wnam.cgi' --data 'key=$license_key''
    license_token=$(${command} | grep token | sed 's|.*token=||' | sed -r 's/<.+//')
    printf "License key: "
    if [ -z $license_token ]; then
        print_red "$license_key is not valid, exiting..."
	exit
    else
        print_green "OK"
    fi
}

if [ "$EUID" -ne 0 ]
  then print_red "Please run as root or with sudo"
  exit
fi
offline=false
curl ya.ru > /dev/null 2>&1
if [ $? -ne 0 ]; then
    offline=true
fi
if [ -z $(which curl) ]; then
    apt update
    apt -y install curl
fi
dir=$(pwd)
if [ -f /home/wnam/wnam-pg.war ]; then
    wnam_pg=1
    wnam_file=wnam-pg.war
else
    wnam_pg=0
    wnam_file=wnam.war
fi
if [ -n "$1" ]; then
    up_file=$1
elif [ -f $wnam_file ] && [ $dir != "/home/wnam" ]; then
    up_file="$dir/$wnam_file"
else
    if $offline ; then
        print_red "Файл обновлений не найден. Загрузка из сети недоступна."
        exit
    else
        if [ $wnam_pg == 0 ]; then
            print_yellow "Файл обновлений не найден. Оновление будет скачано."
            print_yellow_read "Использовать тестовую версию y/n? "
            if [ "$REPLY" == "n" ]; then
                validate_license_key
                wget -O /tmp/wnam.war https://www.netams.com/cgi/download-wnam.cgi?token=$license_token
            else
                wget -O /tmp/wnam.war https://packages.wnam.ru/wnam/1e98eccc-3ab1-4373-95e7-5a2d73a4cab0/wnam.war
            fi
            up_file="/tmp/wnam.war"
        else
            wget -O /tmp/wnam-pg.war https://packages.wnam.ru/wnam/1e98eccc-3ab1-4373-95e7-5a2d73a4cab0/wnam-pg.war
            up_file="/tmp/wnam-pg.war"
        fi
    fi
fi
if [[ "$up_file" =~ $wnam_file ]]; then
    sha_old=($(sha256sum /home/wnam/$wnam_file))
    sha_new=($(sha256sum $up_file))
    if [ $sha_new != $sha_old ]; then
        cd /home/wnam
        systemctl stop wnam
        mv $wnam_file{,.old}
        mv "$up_file" .
        chmod +x $wnam_file
        chown wnam:wnam $wnam_file
        systemctl daemon-reload
        rm logs/*
        systemctl start wnam
    else
        print_red "Файлы одинаковы. Обновление не требуется"
    fi
else
    print_red "Неподходящий файл обновления"
    rm $up_file
fi
