#!/bin/sh
WEB_ROOT=/opt/share/www/nod32  #    ,    
AVBASE_DIR=base # ,    
SERVER=http://update.eset.com #,  
LOG=$WEB_ROOT/log.txt #  
#        
KEYSFILE_DIR=/tmp/harddisk/Passw
KEY_F=$WEB_ROOT/key.txt #      ( )
NTEL=380636336363 #  ,   SMS  

#############################################################################
#                  - !!!!!                       #
#   DIR=nod_upd #      2           #
    DIR=eset_upd #      3  ESS  #
#############################################################################

senderror() {
    echo Sending error message to phone \($SEND_ERROR\) >> $LOG
    DATE=`date +'%d.%m %T'`
    /opt/etc/sendsms/sendtime.php 9 23 $NTEL $DATE, NOD32 updating: $SEND_ERROR
}

trace_error() {
# Argument:
# $1 - Fatal Error: fatal
if [ "$1" = "fatal" ]; then
    echo -n "Fatal error: " >> $LOG
fi
echo $LOG_ERROR >> $LOG
echo $STATUS_ERROR > $WEB_ROOT/status.txt
if [ "$1" = "fatal" ]; then
if [ -n "$SEND_ERROR" ]; then senderror; fi
    clear_tmp
    echo Abort >> $LOG
    pid_file 0
    exit
fi
}

pid_file() {
#   -   -
if [ -z "$1" ]; then
    if [ ! -f "/opt/var/run/nodupd_$AVBASE_DIR.pid" ]; then
        echo $$ > /opt/var/run/nodupd_$AVBASE_DIR.pid
    else
        echo Updating mirror NOD32 is running. Please, wait.
        echo If you are sure that process is not started remove /opt/var/run/nodupd_$AVBASE_DIR.pid
        exit
    fi
else   #   -  -
    rm -f /opt/var/run/nodupd_$AVBASE_DIR.pid
fi
}

unpack_file() {
    mv -f update.ver update.rar
    /opt/bin/unrar x -y -inul update.rar
    if [ ! -f "update.ver" ]; then
        cp -f -p update.rar update.ver
    fi
}

clear_tmp() {
    echo Clearing tmp >> $LOG
    cd $WEB_ROOT/$AVBASE_DIR/tmp 2>/dev/null
    rm -f update.rar
    rm -f update.old
    rm -f update.ver
    rm -r -f $WEB_ROOT/$AVBASE_DIR/tmp
}

dl_file() {
# Arguments:
# 1 - If Errors - prepare to Abort? "1" - Yes, "0" - No
# 2 - File name to download
# 3 - Login
# 4 - Password
#USER_dl=$3
#PASS_dl=$4
RETURN_CODE=0
until /opt/bin/wget -nv -N -a $LOG --cache=off -t 2 --connect-timeout=5 --read-timeout=60 --http-user=$USER --password=$PASS $2; do
    Auth=`sed '$!N;$!D' $LOG | grep 'Authorization failed'`
    if [ ${#Auth} != 0 ]; then
        dl_keys
        load_username
#       USER_dl=$USER; PASS_dl=$PASS
    else
        LOG_ERROR="Error downloading file $2"
        STATUS_ERROR="Error downloading $2"
        SEND_ERROR="Error downloading file $2"
        if [ "$1" = "1" ]; then
            mv $WEB_ROOT/$AVBASE_DIR/update.tmp $WEB_ROOT/$AVBASE_DIR/update.tmp.old 2>/dev/null
            rm -f $WEB_ROOT/$AVBASE_DIR/update.new
            trace_error fatal
        else trace_error
        fi
        RETURN_CODE=1
        break
    fi
done
return $RETURN_CODE
}

dl_keys() {
if [ -z $once_dl_keys ]; then
    once_dl_keys=1
    echo -n Downloading list of keys... >> $LOG
    OLDPWD=$PWD
    cd $KEYSFILE_DIR
    /opt/bin/wget -nd --timestamping -o login_and_password.txt.log http://werzilla.ru/login_and_password.txt
    if [ $? != 0 ]; then
        rm -f $WEB_ROOT/$AVBASE_DIR/update.new
        echo Error >> $LOG
        LOG_ERROR="Error downloading list of keys"
        STATUS_ERROR="Error downloading list of keys"
        SEND_ERROR="Error downloading list of keys"
        trace_error fatal
    fi
    cd $OLDPWD
    echo Ok >> $LOG
    #    ESS     
    ess_keys=$(sed '1,/ESS/d' $KEYSFILE_DIR/login_and_password.txt)
    #     ess_keys
fi

#    username  password
echo -n Get new username and password from list...>> $LOG
USER=$(echo "$ess_keys"|sed '/^Username: */!d; s///;q')
PASS=$(echo "$ess_keys"|sed '/^Password: */!d; s///;q')
EXPIRY=$(echo "$ess_keys"|sed '/^Expiry Date: */!d; s///;q')

#       
ess_keys=$(echo "$ess_keys"|sed '1,/^Expiry Date */d')

if [ -z $USER ]; then
    rm -f $KEY_F
    echo Error >> $LOG
    LOG_ERROR="Corrected username and password not found"
    STATUS_ERROR="Corrected user \& pass not found"
    SEND_ERROR="Corrected username and password not found."
    trace_error fatal
else
    #        
    echo -n Saving... >> $LOG
    echo $USER|tr -d '\015' > $KEY_F
    echo $PASS|tr -d '\015' >> $KEY_F
    echo $EXPIRY|tr -d '\015' >> $KEY_F
    echo Ok >> $LOG
fi
}

load_username() {
#         
echo Loading username \& password from file >> $LOG
USER=$(cat $KEY_F|sed -n '1,1p')
PASS=$(cat $KEY_F|sed -n '2,2p')
EXPIRY=$(cat $KEY_F|sed -n '3,3p')
echo Username: $USER >> $LOG
echo Password: $PASS >> $LOG
echo Expiry Date: $EXPIRY >> $LOG
}

pid_file

DATE=`date +'%Y-%m-%d %T'`
echo $DATE Start NOD32 Updating script. ver 0.5. PID: $$ > $LOG

#      ?
#   -     
if [ ! -f "$KEY_F" ]; then dl_keys; fi

#      
load_username

echo Updating... > $WEB_ROOT/status.txt

#       
mv $WEB_ROOT/$AVBASE_DIR/update.ver $WEB_ROOT/$AVBASE_DIR/update.tmp 2>/dev/null

mkdir -p $WEB_ROOT/$AVBASE_DIR
mkdir -p $WEB_ROOT/$AVBASE_DIR/tmp
cd $WEB_ROOT/$AVBASE_DIR/tmp
echo Downloading update.ver >> $LOG
dl_file 0 $SERVER/$DIR/update.ver
if [ $? != 0 ]; then
#   -      
    mv $WEB_ROOT/$AVBASE_DIR/update.tmp $WEB_ROOT/$AVBASE_DIR/update.ver 2>/dev/null
    clear_tmp
    echo Abort >> $LOG
    pid_file 0
    exit
fi
unpack_file
echo Read list of Servers...>> $LOG
SERVERS=`grep Other= update.ver|grep -v 'Telefonica-Other='|sed s/Other=//|tr -d "\r"|sed s/,/'\n'/g|sed s/^.*@//|sed s/$DIR//|sed s/'\n'/' '/|sed 1d`
rm -f update.ver
rm -f update.rar
mv $WEB_ROOT/$AVBASE_DIR/update.tmp.old $WEB_ROOT/$AVBASE_DIR/update.tmp  2>/dev/null
# 1st - check new version on servers -------------------------------------------------------------------
for UPDSERVERS in $SERVERS; do
    if [ -f $WEB_ROOT/$AVBASE_DIR/update.tmp ]; then
      cp -f -p $WEB_ROOT/$AVBASE_DIR/update.tmp $WEB_ROOT/$AVBASE_DIR/tmp/update.old
    fi
    echo Checking $UPDSERVERS >> $LOG
    dl_file 0 $UPDSERVERS/$DIR/update.ver
    if [ $? = 1 ]; then
      echo Skipping $UPDSERVERS >> $LOG
    else
      unpack_file
      if [ "update.ver" -nt "update.old" ]; then
          echo Found new update.ver >> $LOG
          IFS=[
          echo Parsing new update.ver >> $LOG
# 2nd - parsing update.ver -----------------------------------------------------------------------------
        for section in `cat update.ver|sed '1s/\[//;s/^ *//'|grep -v '^#'|grep -v '^$'`; do
#########################################################################################
#                                        #               #
            sect=$(echo $section|sed 's/^.*_CZECH_.*]/DELETE]/')        #        #
#           sect=$(echo $sect|sed 's/^.*_ENGLISH_.*]/DELETE]/')         #     #
            sect=$(echo $sect|sed 's/^.*_FRENCH_.*]/DELETE]/')          #     #
            sect=$(echo $sect|sed 's/^.*_GERMAN_.*]/DELETE]/')          #       #
            sect=$(echo $sect|sed 's/^.*_ITALIAN_.*]/DELETE]/')         #    #
            sect=$(echo $sect|sed 's/^.*_JAPANESE_.*]/DELETE]/')        #       #
            sect=$(echo $sect|sed 's/^.*_POLISH_.*]/DELETE]/')          #       #
            sect=$(echo $sect|sed 's/^.*_PORTUGUESE_.*]/DELETE]/')      #  #
            sect=$(echo $sect|sed 's/^.*_SLOVAK_.*]/DELETE]/')          #      #
            sect=$(echo $sect|sed 's/^.*_SPANISH_.*]/DELETE]/')         #      #
            sect=$(echo $sect|sed 's/^.*_CROATIAN_.*]/DELETE]/')        #     #
            sect=$(echo $sect|sed 's/^.*_HUNGARIAN_.*]/DELETE]/')       #     #
            sect=$(echo $sect|sed 's/^.*_CHINESE_.*]/DELETE]/')         #      #
            sect=$(echo $sect|sed 's/^.*_DUTCH_.*]/DELETE]/')           #        #
#########################################################################################
#           x64
            sect=$(echo $sect|sed 's/^.*64.]/DELETE]/')

#########################################################################################################################
#                                                                                    #
#                                                                                           #
#           sect=$(echo $sect|sed 's/^CONTINUOUS_.*]/DELETE]/;s/^REVERSE_.*]/DELETE]/;s/^PRELIMINARY_.*]/DELETE]/')     #
#########################################################################################################################
            sect=$(echo $sect|sed 's/^VER]/DELETE]/;s/^HOSTS]/DELETE]/;s/^Expire]/DELETE]/;s/^SETUP]/DELETE]/;s/^COMPATLIST]/DELETE]/;s/^data0001]/DELETE]/')
            if [ -z $(echo $sect|grep '^DELETE]') ]; then
                eval $(echo $sect|tr -d "\r"|grep 'file='|sed 's/ *=/=/;s/= */=/')
                # set version 
                if [ ! -z $(echo $sect|grep '^ENGINE2]') ]; then
                  version=$(echo $sect|sed '/^version=*/!d; s///;q'|tr -d '\015')
                else
                  if [ ! -z $(echo $sect|grep '^ENGINE1]') ]; then
                    version=$(echo $sect|sed '/^version=*/!d; s///;q'|tr -d '\015')
                  fi
                fi
                cd $WEB_ROOT/$AVBASE_DIR
                echo Checking file: $UPDSERVERS/$file >> $LOG
                dl_file 1 $UPDSERVERS/$file
                #$USER $PASS
                cd $WEB_ROOT/$AVBASE_DIR/tmp
                echo [$(echo $sect|sed 's/file=.*\//file=/') >> $WEB_ROOT/$AVBASE_DIR/update.new
            fi
        done
# 2nd ----------------------------------------------------------------------------------------------------
        IFS=' '
        # .new file to .ver & set new file date
        cd $WEB_ROOT/$AVBASE_DIR
        if [ -f "update.new" ]; then
          mv -f update.new update.tmp
          /opt/bin/touch -am -r ./tmp/update.ver update.tmp
         echo Sucessfully downloads new updates >> $LOG
        fi
        cd $WEB_ROOT/$AVBASE_DIR/tmp
      fi
    fi # Skipping server
done
# 1st -----------------------------------------------------------------------------------------------------

clear_tmp

#     
mv $WEB_ROOT/$AVBASE_DIR/update.tmp $WEB_ROOT/$AVBASE_DIR/update.ver 2>/dev/null

cd $WEB_ROOT

# Set Status 
echo Ok > status.txt

if [ -n "$version" ]; then
  echo Base version: $version >> $LOG
  echo $version > ver.txt
  echo Create packed Base... >> $LOG
  tar cf base.tar base/*
fi

DATE=`date +'%Y-%m-%d %T'`
echo $DATE NOD32 Updating script successfully completed. >> $LOG

pid_file 0