#!/bin/sh
#-------------------------------------------------------------------------------
# charon_menu_sendlogs
#-------------------------------------------------------------------------------
# Copyright (C) 2013-2022 STROMASYS.
# All rights reserved.
#
#set -x
VERSION=1.13

. `dirname $0`/charon_common
. `dirname $0`/charon_common_menu

LOGFLIST="${CHARONDIR}/utils/charon_logchk.list"
LOGFLSTMAIL=/tmp/`basename $0`.logflstmail
BOOTLIST="${CHARONDIR}/utils/charon_gstart.boot"
MAXLOGLINES=64
MAILFRFILE="${CHARONDIR}/utils/charon_check.mailfrom"

function add_log_to_mail
{
  echo ${LINE} >>${LOGFLSTMAIL}
  if test "${MAILMODE}" = "TEXT"
  then
    #-----------
    # TEXT mode
    #-----------
    echo "----------------------------------------------------------------------------" >>${TMPMAIL}
    if test "${LINE}" = "$1"
    then
      echo "Current log file: ${LINE}" >>${TMPMAIL}
    else
      N=N+1
      echo "Log file -${N}: ${LINE}" >>${TMPMAIL}
    fi
    echo "----------------------------------------------------------------------------" >>${TMPMAIL}
    if test `wc -l ${LINE} | awk '{print $1}'` -gt ${MAXLOGLINES}
    then
      echo "(truncated)" >>${TMPMAIL}
      tail -${MAXLOGLINES} ${LINE} >>${TMPMAIL}
    else
      cat ${LINE} >>${TMPMAIL}
    fi
    echo >>${TMPMAIL}
  else
    #-----------
    # HTML mode
    #-----------
    echo "<font color=#0a71b4>" >>${TMPMAIL}
    if test "${LINE}" = "$1"
    then
      echo "<b>Current log file</b>: ${LINE}<br>" >>${TMPMAIL}
    else
      N=N+1
      echo "<b>Log file -${N}</b>: ${LINE}<br>" >>${TMPMAIL}
    fi
    echo "</font>" >>${TMPMAIL}
    if test `wc -l ${LINE} | awk '{print $1}'` -gt ${MAXLOGLINES}
    then
      echo "<font color=#3e3e40>(truncated to last ${MAXLOGLINES} lines)</font><br>" >>${TMPMAIL}
      CMD="tail -${MAXLOGLINES}"
    else
      CMD="cat"
    fi

    ${CMD} ${LINE} 2>&1 | grep -v "^$" | while read LI
    do
      case "`echo ${LI} | cut -f3 -d:`"
      in
        "warn")
          echo "<font style='background-color:#FF4500'>" >>${TMPMAIL}
          ;;
        "err")
          echo "<font color=#f0f0f0 style='background-color:#B22222'>" >>${TMPMAIL}
          ;;
        "ERR")
          echo "<font color=#f0f0f0 style='background-color:#FF2020'>" >>${TMPMAIL}
          ;;
        "Charon-PAR"|"Charon-HPA")
          echo "<font style='background-color:#00ff00'>" >>${TMPMAIL}
          ;;
        "log file"|"config load")
          echo "<font color='#0062ab'>" >>${TMPMAIL}
          ;;
        "System model"|"RAM size"|"Host CPU freq")
          echo "<font color='#0062ab'>" >>${TMPMAIL}
          ;;
        "Found license key"|"License number")
          echo "<font style='background-color:#00ff00'>" >>${TMPMAIL}
          ;;
        "emulator is about to exit")
          echo "<font color=#ff2020>" >>${TMPMAIL}
          ;;
        "starting the emulator")
          echo "<font style='background-color:#00ff00'>" >>${TMPMAIL}
          ;;
        "run cpu loop")
          #--- Up to Version 3.0.0
          echo "<font style='background-color:#00ff00'>" >>${TMPMAIL}
          ;;
        cpu*)
          #--- Starting with Version 3.0.1
          if test -n "`echo ${LI} | grep 'run cpu loop'`"
          then
            echo "<font style='background-color:#00ff00'>" >>${TMPMAIL}
          fi
          ;;
        "exit")
          echo "<font color=#ffffff style='background-color:#ff2020'>" >>${TMPMAIL}
          ;;
        *)
          if test -n "`echo ${LINE} | grep 'Got connection from'`"
          then
            echo "<font color=#ffffff style='background-color:#404040'>" >>${TMPMAIL}
          fi
          ;;
      esac

      if test -n "`echo ${LI} | grep :WARNING:`"
      then
        echo "<font style='background-color:#FF4500'>" >>${TMPMAIL}
      fi
      if test -n "`echo ${LI} | grep :ERROR:`"
      then
        echo "<font color=#f0f0f0 style='background-color:#B22222'>" >>${TMPMAIL}
      fi
      if test -n "`echo ${LI} | grep :FATAL:`"
      then
        echo "<font color=#f0f0f0 style='background-color:#FF2020'>" >>${TMPMAIL}
      fi

      echo "<font style='font-family:monospace;'>${LI}</font></font><br>" >>${TMPMAIL}
    done
    echo "<br>" >>${TMPMAIL}
  fi
}

while test 1
do
  display_header "Send configuration and log files via mail"
  echo
  if test `id -u` -ne 0
  then
    tput bold
    echo "Must be root !"
    tput sgr0
    Press_Enter
    echo
    exit 1
  fi

  display_guestslist -num
  NGUESTS=`grep -v ^# ${BOOTLIST} | wc -l`
  if test ${NGUESTS:-0} -eq 0
  then 
    tput bold
    echo "Guests list is empty."
    tput sgr0
    break 
  fi
  if test ${NGUESTS:-0} -eq 1
  then
    ANS=1
  else
    echo
    echo -n "Select the guest (q to quit): "
    read ANS
    test "${ANS}" = "q" && break
  fi
  if test -n "${ANS}"
  then
    if test -z "`echo ${ANS} | tr -d [0123456789]`"
    then
      if test ${ANS} -lt 1 -o ${ANS} -gt `grep -v ^# ${BOOTLIST} | wc -l`
      then
        tput bold
        echo "Incorrect value, out of range."
        tput sgr0
        sleep 3
      else
        echo
        CFG=`grep -v ^# ${BOOTLIST} | head -${ANS} | tail -1 | cut -f2 -d';'`
        get_logfile ${CFG}
        CFGH=`basename ${CFG}|sed "s=\.cfg$==g"`

        select_mailto
        if test -s /root/.charon.recipient
        then
          echo
          while test 1
          do
            echo -n "Number of logs to send [default = 3 latest] '('q' to quit) : "
            read NL
            case "${NL}"
            in
              [1-9]|[1-9][0-9]|"")
                test -z "${NL}" && NL=3

                MAILTO=`cat /root/.charon.recipient`
                echo
                TMPMAIL=/tmp/charon_menu_sendlogs.$$
                echo "Preparing email..."

                BOUNDARY="$$CHARONSENDMAIL`basename $0`$$"

                MAILFROM=`cat ${MAILFRFILE} 2>/dev/null`
                if test -z "${MAILFROM}"
                then
                  echo "From: `whoami`@`hostname`" >${TMPMAIL}
                else
                  if test -n "`echo ${MAILFROM} | grep '@'`"
                  then
                    echo "From: ${MAILFROM}" >${TMPMAIL}
                  else
                    echo "From: ${MAILFROM}<`whoami`@`hostname`>" >${TMPMAIL}
                  fi
                fi

                echo "To: ${MAILTO}" >>${TMPMAIL}
                echo "Subject: [CHARON] Configuration and log files for ${CFGH}" >>${TMPMAIL}
                echo "Mime-Version: 1.0;" >>${TMPMAIL}
                echo "Content-Type: multipart/mixed; boundary=${BOUNDARY}" >>${TMPMAIL}
                echo "" >>${TMPMAIL}
                echo "Please find attached configuration and log files for ${CFGH}" >>${TMPMAIL}
                echo "" >>${TMPMAIL}

                echo "--${BOUNDARY}" >>${TMPMAIL}
                MAILMODE=`cat /root/.charonmailmode 2>/dev/null`
                rm -f ${LOGFLSTMAIL} 2>/dev/null
                if test "${MAILMODE}" = "TEXT"
                then
                  #--------------------------------
                  # Plain TEXT mode
                  #--------------------------------
                  echo "Content-Type: text/plain; charset=\"ISO-8859-1\";" >>${TMPMAIL}
                  echo "" >>${TMPMAIL}
                  echo "Please find attached configuration and log files for ${CFGH}" >>${TMPMAIL}
                  echo "" >>${TMPMAIL}
                  echo "" >>${TMPMAIL}
                  echo "----------------------------------------------------------------------------" >>${TMPMAIL}
                  echo "Configuration file" >>${TMPMAIL}
                  echo "----------------------------------------------------------------------------" >>${TMPMAIL}
                  cat ${CFG} >>${TMPMAIL}
                  echo "" >>${TMPMAIL}

                  typeset -i N=0
                  if test -L ${LOGF}
                  then
                    LOGFLINK=`dirname ${LOGF}`"/"`file ${LOGF}|cut -f2 -d'\`'|tr -d "'"`
                    ls -1tR `echo ${LOGF} | sed "s=\.log==g"`.??????-??????-????.log 2>/dev/null | head -${NL:-3} | while read LINE
                    do
                      add_log_to_mail ${LOGFLINK}
                    done
                  else
                    ls -1tR ${LOGF} ${LOGF}.upto* 2>/dev/null | head -${NL:-3} | while read LINE
                    do
                      add_log_to_mail ${LOGF}
                    done
                  fi
                  echo "" >>${TMPMAIL}

                  #--------------------------------
                  # Adding TEXT footer
                  #--------------------------------
                  if test -s ${CHARONDIR}/utils/charon_check.mailfooter
                  then
                    echo "----------------------------------------------------------------------------" >>${TMPMAIL}
                    cat ${CHARONDIR}/utils/charon_check.mailfooter | sed -e "s=<br>==g" \
                        -e "s=<b>==g"     -e "s=</b>==g" \
                        -e "s=</font>==g" -e "s=<font .*>==g" \
                        -e "s=</a>==g"    -e "s=<a .*>==g"    >>${TMPMAIL}
                  fi
                else
                  #--------------------------------
                  # HTML mode
                  #--------------------------------
                  echo "Content-Type: text/html; charset=\"ISO-8859-1\";" >>${TMPMAIL}
                  echo "Content-Disposition: inline;" >>${TMPMAIL}
                  echo "" >>${TMPMAIL}
                  echo "<html>" >>${TMPMAIL}
                  echo "<font color=#0a71b4>Please find attached configuration and log files for ${CFGH}</font><br>" >>${TMPMAIL}

                  echo "<br>" >>${TMPMAIL}
                  echo "<b>Configuration file</b><br>" >>${TMPMAIL}
                  echo "<hr color=#0a71b4>" >>${TMPMAIL}
                  echo "<font style='font-family:monospace;'>" >>${TMPMAIL}

                  cat ${CFG} 2>&1 | while read LI
                  do
                    if test "`echo ${LI} | cut -c1`" = "#"
                    then
                      if test "`echo ${LI} | cut -c1-6`" = "#INFO:"
                      then
                        echo "<font color='#0a71b4'>" >>${TMPMAIL}
                      else
                        echo "<font color='#a0a0a0'>" >>${TMPMAIL}
                      fi
                    fi
                    echo "${LI}<br>"  >>${TMPMAIL}
                    test "`echo ${LI} | cut -c1`" = "#" && echo "</font>" >>${TMPMAIL}
                  done

                  echo "</font>" >>${TMPMAIL}
                  echo "<br>" >>${TMPMAIL}

                  echo "<b>Log files</b><br>" >>${TMPMAIL}
                  echo "<hr color=#0a71b4>" >>${TMPMAIL}

                  typeset -i N=0
                  if test -L ${LOGF}
                  then
                    LOGFLINK=`dirname ${LOGF}`"/"`file ${LOGF}|cut -f2 -d'\`'|tr -d "'"`
                    ls -1tR `echo ${LOGF} | sed "s=\.log==g"`.??????-??????-????.log 2>/dev/null | head -${NL:-3} | while read LINE
                    do
                      add_log_to_mail ${LOGFLINK}
                    done
                  else
                    ls -1tR ${LOGF} ${LOGF}.upto* 2>/dev/null | head -${NL:-3} | while read LINE
                    do
                      add_log_to_mail ${LOGF}
                    done
                  fi

                  #--------------------------------
                  # Adding HTML footer
                  #--------------------------------
                  if test -s ${CHARONDIR}/utils/charon_check.mailfooter
                  then
                    echo "<br>" >>${TMPMAIL}
                    echo "<hr color=#0a71b4>" >>${TMPMAIL}
                    cat ${CHARONDIR}/utils/charon_check.mailfooter | sed "s=$=<br>=g" >>${TMPMAIL}
                  fi

                  echo "</html>" >>${TMPMAIL}
                fi
                echo "" >>${TMPMAIL}

                #--------------------------------
                # Zipping files
                #--------------------------------
                ZIPF="/tmp/"`basename ${CFG} | sed "s=\.=_=g"`"logs.zip"
                rm -f ${ZIPF} 2>/dev/null
                zip -j ${ZIPF} ${CFG} `cat ${LOGFLSTMAIL}` >/dev/null 2>&1

                #--------------------------------
                # Attaching file
                #--------------------------------
                echo "--${BOUNDARY}" >>${TMPMAIL}
                echo "Content-Type: application/octet-stream; name=`basename ${ZIPF}`;" >>${TMPMAIL}
                echo "Content-Transfer-Encoding: base64;" >>${TMPMAIL}
                echo "Content-Disposition: Attachment; filename=`basename ${ZIPF}`" >>${TMPMAIL}
                echo "" >>${TMPMAIL}
                base64 ${ZIPF} >>${TMPMAIL}
                echo "" >>${TMPMAIL}

                #---------------------------------------------
                # Attaching charon-report file (if available)
                #---------------------------------------------
                if test -x ${CHARONDIR}/bin/charon-report
                then
                  echo "Generating the charon-report..."
                  tput bold
                  echo -n "Enter issue description: "
                  tput sgr0
                  D=`date +%Y%m%d`
                  rpm -q hpa >/dev/null
                  if test  $? -eq 0
                  then
                    read ISSUEDESC
                    (echo "${ISSUEDESC}";echo) | ${CHARONDIR}/bin/charon-report -f `dirname ${CFG}` >/dev/null
                    ZIPF=`ls -tr /root/report-${D}-*.tgz | tail -1`
                  else
                    ${CHARONDIR}/bin/charon-report -f `dirname ${CFG}` >/dev/null
                    ZIPF=`ls -tr /tmp/report-${D}-*.tgz | tail -1`
                  fi
                  if test -e ${ZIPF}
                  then
                    if test `ls -s ${ZIPF} | awk '{print $1}'` -gt 5000000
                    then
                      echo "The size of the ${ZIPF} file is above 5Mb. Cannot attach to mail."
                    else
                      echo "Adding the file ${ZIPF} to attachments..."
                      echo "--${BOUNDARY}" >>${TMPMAIL}
                      echo "Content-Type: application/octet-stream; name=`basename ${ZIPF}`;" >>${TMPMAIL}
                      echo "Content-Transfer-Encoding: base64;" >>${TMPMAIL}
                      echo "Content-Disposition: Attachment; filename=`basename ${ZIPF}`" >>${TMPMAIL}
                      echo "" >>${TMPMAIL}
                      base64 ${ZIPF} >>${TMPMAIL}
                      echo "" >>${TMPMAIL}
                      echo "--${BOUNDARY}--" >>${TMPMAIL}
                    fi
                  fi
                fi

                echo "Sending files to ${MAILTO}..."

                /usr/sbin/sendmail -t -i <${TMPMAIL}
                if test $? = 0
                then
                  echo "Done."
                  # rm -f ${TMPMAIL}
                else
                  echo "Failed!"
                fi
                Press_Enter
                break
                ;;
              "q")
                break
                ;;
            esac
          done
        fi
        test ${NGUESTS:-0} -eq 1 && break
      fi
    else
      tput bold
      echo "Incorrect value, must be numeric."
      tput sgr0
      sleep 3
    fi
  fi
done

exit
