#!/bin/sh

. $(dirname $0)/nod32upd.conf

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
    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
  fi
  clear_tmp
  echo Abort >> $LOG
  pid_file 0
  exit
fi
}

pid_file() {
#   -   -
if [ -z "$1" ]; then
    if [ ! -f "/opt/var/run/nod32upd.pid" ]; then
        echo $$ > /opt/var/run/nod32upd.pid
    else
        echo Updating mirror NOD32 is running. Please, wait.
        echo If you are sure that process is not started remove /opt/var/run/nod32upd.pid
        exit
    fi
else   #   -  -
    rm -f /opt/var/run/nod32upd.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
RETURN_CODE=0
until /opt/bin/wget -U 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.8) Gecko/20050511' -nv -N -a $LOG --cache=off -t 2 --connect-timeout=5 --read-timeout=60 --http-user=$USER --password=$PASS $2; do
    Auth=`/opt/bin/sed '$!N;$!D' $LOG | grep 'Authorization failed'`
    if [ ${#Auth} != 0 ]; then
      dl_keys
      load_username
    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() {
USER=''
PASS=''
until [ -z "$HTMLs_list" ] && [ -z "$keys" ]; do
#           .
  if [ -z "$keys" ]; then
  #         
    #   .
    KEYS_HTML=$(echo "$HTMLs_list" | /opt/bin/sed 's/,.*//')
    #     
    HTMLs_list=$(echo "$HTMLs_list" | /opt/bin/sed -n 's/[^,]*,//p')
    #   .
    echo -n Downloading list of keys $KEYS_HTML... >> $LOG
    /opt/bin/wget -O $WEB_ROOT/keys.html -o $WEB_ROOT/keys.html.log -U 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.8) Gecko/20050511' $KEYS_HTML
    if [ $? != 0 ]; then
      echo Error. >> $LOG
      if [ -z $HTMLs_list ]; then
        #           
        rm -f $WEB_ROOT/$AVBASE_DIR/update.new
        LOG_ERROR="Error downloading list of keys"
        STATUS_ERROR="Error downloading list of keys"
        SEND_ERROR="Error downloading list of keys"
        trace_error fatal
      else
      #     
        continue
      fi
    fi
    echo Ok >> $LOG
    #  
    keys=$(cat $WEB_ROOT/keys.html | /opt/bin/iconv -f cp1251 | /opt/bin/sed 's/<[^<>]*>/\n/g; s/: */:/g' | /opt/bin/sed -n /username:/I,/password:/Ip)
    echo "$keys" > $KEYS_F
  fi
echo -n Get new username and password from list...>> $LOG
until [ -z "$keys" ]; do
#    username  password
USER=$(echo "$keys"|/opt/bin/sed '/^username:*/I!d; s///;q')
PASS=$(echo "$keys"|/opt/bin/sed '/^password:*/I!d; s///;q')

#       
keys=$(echo "$keys"|/opt/bin/sed '1,/^password:*/Id')

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

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

pid_file

DATE=`date +'%Y-%m-%d %T'`
echo $DATE Start NOD32 Updating script. ver $VER. 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='|/opt/bin/sed s/Other=//|tr -d "\r"|/opt/bin/sed s/,/'\n'/g|/opt/bin/sed s/^.*@//|/opt/bin/sed s/$DIR//|/opt/bin/sed s/'\n'/' '/|/opt/bin/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 [ ! -e "update.old" ] || [ "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|/opt/bin/sed '1s/\[//;s/^ *//'|grep -v '^#'|grep -v '^$'`; do
#########################################################################################
#                                        #               #
            sect=$(echo $section|/opt/bin/sed 's/^.*_CZECH_.*]/DELETE]/')        #        #
#           sect=$(echo $sect|/opt/bin/sed 's/^.*_ENGLISH_.*]/DELETE]/')         #     #
            sect=$(echo $sect|/opt/bin/sed 's/^.*_FRENCH_.*]/DELETE]/')          #     #
            sect=$(echo $sect|/opt/bin/sed 's/^.*_GERMAN_.*]/DELETE]/')          #       #
            sect=$(echo $sect|/opt/bin/sed 's/^.*_ITALIAN_.*]/DELETE]/')         #    #
            sect=$(echo $sect|/opt/bin/sed 's/^.*_JAPANESE_.*]/DELETE]/')        #       #
            sect=$(echo $sect|/opt/bin/sed 's/^.*_POLISH_.*]/DELETE]/')          #       #
            sect=$(echo $sect|/opt/bin/sed 's/^.*_PORTUGUESE_.*]/DELETE]/')      #  #
            sect=$(echo $sect|/opt/bin/sed 's/^.*_SLOVAK_.*]/DELETE]/')          #      #
            sect=$(echo $sect|/opt/bin/sed 's/^.*_SPANISH_.*]/DELETE]/')         #      #
            sect=$(echo $sect|/opt/bin/sed 's/^.*_CROATIAN_.*]/DELETE]/')        #     #
            sect=$(echo $sect|/opt/bin/sed 's/^.*_HUNGARIAN_.*]/DELETE]/')       #     #
            sect=$(echo $sect|/opt/bin/sed 's/^.*_CHINESE_.*]/DELETE]/')         #      #
            sect=$(echo $sect|/opt/bin/sed 's/^.*_DUTCH_.*]/DELETE]/')           #        #
#########################################################################################
#           x64
            sect=$(echo $sect|/opt/bin/sed 's/^.*64.]/DELETE]/')

#           EAV and ESS build [eav*] [ess*]
            sect=$(echo $sect|/opt/bin/sed 's/^eav.*/DELETE]/;s/^ess.*]/DELETE]/')

#           ESET Mail Security [emsx*]
            sect=$(echo $sect|/opt/bin/sed 's/^emsx.*/DELETE]/')


#########################################################################################################################
#                                                                                    #
#                                                                                           #
#           sect=$(echo $sect|/opt/bin/sed 's/^CONTINUOUS_.*]/DELETE]/;s/^REVERSE_.*]/DELETE]/;s/^PRELIMINARY_.*]/DELETE]/')     #
#########################################################################################################################

            sect=$(echo $sect|/opt/bin/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='|/opt/bin/sed 's/ *=/=/;s/= */=/')
                # set version 
                if [ ! -z $(echo $sect|grep '^ENGINE2]') ]; then
                  version=$(echo $sect|/opt/bin/sed '/^version=*/!d; s///;q'|tr -d '\015')
                else
                  if [ ! -z $(echo $sect|grep '^ENGINE1]') ]; then
                    version=$(echo $sect|/opt/bin/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|/opt/bin/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

rm -f $WEB_ROOT/keys.ht*

# 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