#!/bin/bash

u=$(whoami)
if [ "x$u" = "x" ]; then exit 0; fi
if [ "x$u" = "xroot" ]; then exit 0; fi
if [ "x$HOME" = "x" ]; then exit 0; fi
# Nur User-Start erlaubt


VIRENSCHUTZ_AKTIVIERT=$(xlinux-settings get XLINUXSECURITY_VIRENSCHUTZ_AKTIVIERT || echo 1)
WARTUNGSSERVICE_AVAILABLE=$(xlinux-settings get WARTUNGSSERVICE_AVAILABLE || echo "0")
E=$(xlinux-settings get SUPPORT_ENDDATE2)
d=$(date "+%Y%m%d")
if [ $E -lt $d ]; then
  # Abbruch wenn Enddate
  echo "Sicherheitspaket abgelaufen."
  exit 1;
fi

showok=0


PID=$$
renice -n 19 $PID &>/dev/null

#function open_admin() {
#  c=$(ps -ef 2>/dev/null | grep xlinux-security-admin | grep -v grep | wc -l)
#  if [ $c -eq 0 ]; then
#    xlinux-security-admin --viren &
#  fi
#}

function remove_from_log() {
  f=$1
  t=$(grep -v "^....-..-.. ..:..:.. ${f}$" "$HOME/.cache/xlinux_virus_found" 2>/dev/null)
  echo "$t" >"$HOME/.cache/xlinux_virus_found"
  t=$(grep -v "^${f}$" "$HOME/.cache/xlinux_virus_found_whitelist" 2>/dev/null)
  echo "$t" >"$HOME/.cache/xlinux_virus_found_whitelist"
}

function scanfile() {
  scfile=$1
  if [[ "$scfile" == "./"* ]]; then
    scfile=${scfile:2}
  fi
  fullpath="$HOME/$scfile"
  if [[ "$scfile" == "/"* ]]; then
    fullpath="$scfile"
  fi
  virus=0
  datum=$(date "+%Y%m%d")
  d=$(date "+%Y-%m-%d %H:%M:%S")
  if [ -f "$fullpath" ]; then
    if [[ "$fullpath" != *"/."* ]]; then
      clamdscan --multiscan --fdpass "$fullpath" >/dev/null 2>&1; r=$?
      if [ $r -ne 2 ]; then
        if [ $r -eq 1 ]; then
          s="Virenverdacht"
          c=$(grep "^$scfile$" ~/.cache/xlinux_virus_found_whitelist | wc -l)
          if [ $c -ne 0 ]; then
            s="Ignoriert"
          fi
        else
          s="Ok";
        fi
        echo "$s|$d|${scfile}" >>"$HOME/.cache/xlinux_virus.scanlog.${datum}"
        echo "$s|$d|${scfile}" >>"/tmp/xlinux_virus.scanlog.short"
        if [ $r -eq 1 ]; then
          t=$(grep -c "^....-..-.. ..:..:.. ${scfile}$" "$HOME/.cache/xlinux_virus_found" 2>/dev/null)
          if [ $t -eq 0 ]; then
            echo "$d ${scfile}" >> "$HOME/.cache/xlinux_virus_found"
            notify-send "Virenverdacht in Datei" "$scfile"
          fi
          #if [[ "x$WHITELIST" != *"|$scfile|"* ]]; then
          #  echo "$d ${scfile:2}" >> "$HOME/.cache/xlinux_virus_found"
          #  notify-send "Virenverdacht in Datei" "$scfile"
          #  virus=1
          #fi
        else
          if [ $showok -eq 1 ]; then
            notify-send "Datei auf Viren geprüft" "$scfile"
          fi
        fi
      fi
    fi
  else
    remove_from_log "${scfile}"
  fi
}

function fullscan_newlist() {
  rm "$HOME/.cache/xlinux_virus.listtoscan" >/dev/null 2>&1
  rm "$HOME/.cache/xlinux_virus.listtoscan.state" 2>/dev/null
  notify-send "Virenschutz gestartet" "$HOME"
  while read file; do
    if [[ "$file" != *"/."* ]]; then
      echo "${file}" >>"$HOME/.cache/xlinux_virus.listtoscan"
    fi
  done < <(cd "$HOME" ; find . -type f)
  
}

function fullscan_worker() {
  start=$(echo $(cat "$HOME/.cache/xlinux_virus.listtoscan.state" 2>/dev/null || echo "0") | cut -d/ -f1) 
  gesamt=$(cat "$HOME/.cache/xlinux_virus.listtoscan" 2>/dev/null | wc -l)
  zaehler=0
  next=$(( $(date +%s) + 3 ))
  if [ $gesamt -gt 0 ]; then
    while read line; do
      zaehler=$(( $zaehler + 1 ))
      echo "$start $zaehler $gesamt"
      if [ $zaehler -gt $start ]; then
        scanfile "$line"
        now=$(date +%s)
        if [ $now -gt $next ]; then
          next=$(( $now + 3 ))
          echo "$zaehler/$gesamt" >"$HOME/.cache/xlinux_virus.listtoscan.state"
        fi
        sleep 0.1
      fi
    done <"$HOME/.cache/xlinux_virus.listtoscan"
  fi
  zeit=$(date "+%Y-%m-%d, %H:%M:%S")
  echo "$zeit|" > "$HOME/.cache/xlinux_virus.fullscanfinished"  
  rm "$HOME/.cache/xlinux_virus.listtoscan.state" 2>/dev/null
  rm "$HOME/.cache/xlinux_virus.listtoscan" 2>/dev/null
  notify-send "Virenscan abgeschlossen" "$HOME"
}

function ondemand_watcher() {
  # Loggt die geänderten Dateien die geprüft werden sollen mit Zeitstempel
  echo "AV-Watcher gestartet" > "$HOME/.cache/xlinux-av.log"
  while read zeit file; do
    if [[ "$file" != *"/."* ]]; then
      # IF ist wichtig, da sonst xlinux-dir-monitor 100% schluckt, da er immer "$HOME/.cache/xlinux-av.log" meldet
      echo "$zeit $file" >>"$HOME/.cache/xlinux-av.log"
      echo "$zeit ./$file" >>/tmp/xlinux-security-av-to-scan
    fi
  done < <(xlinux-dir-monitor "$HOME/" 2>>"$HOME/.cache/xlinux-av.log")
  echo "AV-Watcher beendet." >>"$HOME/.cache/xlinux-av.log"
  #while read file; do
  #  if [[ "$file" != *"/."* ]]; then
  #    datum=$(date "+%s")
  #    echo "$datum ${file}" >> /tmp/xlinux-security-av-to-scan
  #  fi
  #done < <(cd "$HOME" ; inotifywait -m -r -e close_write --format "%w%f" . )
}

function start_worker() {
  #c=$(ps -ef 2>/dev/null | grep 'xlinux-security-av-daemon --ondemand_worker' | grep -v grep | wc -l)
  #if [ $c -eq 0 ]; then
  #  xlinux-security-av-daemon --ondemand_worker &
  #fi
  xlinux-security-av-daemon --ondemand_worker &
  sleep 3
  rm /tmp/t >/dev/null 2>&1
  if [ -f /tmp/xlinux-security-av-to-scan.do ]; then
    cat /tmp/xlinux-security-av-to-scan.do >>/tmp/t
    rm /tmp/xlinux-security-av-to-scan.do &>/dev/null
  fi
  if [ -f "$HOME/.cache/xlinux_virus_found" ]; then
    datum=$(date "+%s")
    while read f1 f2 f3; do
      echo $datum $f3 >>/tmp/t
    done <"$HOME/.cache/xlinux_virus_found"
    rm "$HOME/.cache/xlinux_virus_found" &>/dev/null
  fi
  if [ -f "/tmp/t" ]; then
    cat /tmp/t >>/tmp/xlinux-security-av-to-scan
  fi
}

function wait_for_new_files() {
  notify-send "Virenschutz gestartet"
  while true; do
    if [ -f "$HOME/.cache/xlinux-security-last-search" ]; then
      s=$(cat "$HOME/.cache/xlinux-security-last-search")
    else
      s=0
    fi
    rm "/tmp/xlinux-security-av-to-scan" &>/dev/null
    s1=$(date +%s)
    while read f; do
      if [[ "$f" != *"/."* ]]; then
        echo "$f" >>"/tmp/xlinux-security-av-to-scan"
      fi
    done < <(cd "$HOME" ; find . -type f -newermt @$s -o -type f -newerct @$s )
    if [ -f "/tmp/xlinux-security-av-to-scan" ]; then
      mv "/tmp/xlinux-security-av-to-scan" "$HOME/.cache/xlinux-security-av-to-scan.$s"
    fi
    echo "$s1" >"$HOME/.cache/xlinux-security-last-search"
    sleep 10
  done
}

function wait_for_scan_task() {
  # Arbeitet das Logfile von filechange_watcher() ab.
  w="$HOME/.cache/xlinux-security-av-to-scan"
  while true; do
    f=$(ls "$HOME"/.cache/xlinux-security-av-to-scan.* 2>/dev/null | head -1)
    if [ "x$f" == "x" ]; then
      # Keine Datei zu scannen
      sleep 5
    else
      t_end=$(( $(date +%s) + 10 ));
      mv "$f" "$f.u"
      while read file_to_scan; do
        t=$(date +%s)
        if [ $t -lt $t_end ]; then
          scanfile "$file_to_scan"
        else
          echo "$file_to_scan" >>"$f"
        fi
      done <"$f.u"
      rm "$f.u" &>/dev/null
    fi
  done
}

# WHILELIST LADEN
function load_whitelist() {
  WHITELIST=""
  if [ -f "$HOME/.cache/xlinux_virus.whitelist" ]; then
    while read f; do
      WHITELIST="$WHITELIST|$f"
    done < "$HOME/.cache/xlinux_virus.whitelist"
    WHITELIST="$WHITELIST|"
  fi
}

function av_off() {
  notify-send "Virenschutz angehalten"
  pkill -f "$SELF --scantask"
  pkill -f "$SELF --ondemand_worker"
  pkill -f "$SELF --wait_file_write"
  pkill -f "$SELF --wait_new_files"
}


# die letzten 200 Zeilen Logfile rekonstruieren
rm -f "/tmp/xlinux_virus.scanlog.short" &>/dev/null
cat "$HOME/.cache/xlinux_virus.scanlog."* | tail -200 >"/tmp/xlinux_virus.scanlog.short"



option=$1
scfile=$2
SELF=$0


case "$option" in
  --off)
    av_off
    ;;
  --ondemand)
    $SELF --scantask &
    #$SELF --wait_file_write &
    $SELF --wait_new_files &
    ;;
  --scan|--scanfile)
    showok=1
    scanfile "$scfile"
    ;;
  --ondemand_worker|--scantask)
    wait_for_scan_task
    ;;
  --wait_file_write)
    ondemand_watcher
    ;;
  --wait_new_files)
    wait_for_new_files
    ;;
  *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 0
    ;;
esac
exit 0
