#!/bin/bash

PATH=/usr/local/bin:/usr/local/sbin:/opt/local/bin:/usr/bin:/usr/sbin:/bin:/sbin
SHELL=/bin/bash

_TODAY=`date +%y%m%d`
_NOW=`date +%y%m%d-%H%M`
_CHECK_HOST=`uname -n`
_LOG_DIR="/var/backups/reports/up/$(basename "$0")/$_TODAY"
_UP_LOG="$_LOG_DIR/$(basename "$0")-up-$_NOW.log"
_L_VMFAMILY=XEN
_L_VM_TEST=`uname -a 2>&1`
if [[ "$_L_VM_TEST" =~ beng ]] ; then
  _L_VMFAMILY="VS"
fi

send_report ()
{
  if [ -e "/root/.barracuda.cnf" ] ; then
    source /root/.barracuda.cnf
    if [ -e "/root/.host8.cnf" ] || [[ "$_CHECK_HOST" =~ ".host8." ]] || [ "$_L_VMFAMILY" = "VS" ] ; then
      _MY_EMAIL="$(basename "$0")@omega8.cc"
    fi
    if [ ! -z "$_MY_EMAIL" ] ; then
      cat $_UP_LOG | mail -e -s "REPORT: Successful Barracuda upgrade on $_CHECK_HOST at $_NOW" $_MY_EMAIL
      echo "REPORT: Successful Barracuda upgrade on $_CHECK_HOST sent to $_MY_EMAIL"
    fi
  fi
}

send_alert ()
{
  if [ -e "/root/.barracuda.cnf" ] ; then
    source /root/.barracuda.cnf
    if [ -e "/root/.host8.cnf" ] || [[ "$_CHECK_HOST" =~ ".host8." ]] || [ "$_L_VMFAMILY" = "VS" ] ; then
      _MY_EMAIL="$(basename "$0")@omega8.cc"
    fi
    if [ ! -z "$_MY_EMAIL" ] ; then
      cat $_UP_LOG | mail -e -s "ALERT: Failed Barracuda upgrade on $_CHECK_HOST at $_NOW" $_MY_EMAIL
      echo "ALERT: Failed Barracuda upgrade on $_CHECK_HOST sent to $_MY_EMAIL"
    fi
  fi
}

check_report ()
{
  _SEND_ALERT=NO
  _RESULT_TEST_OK=$(grep "INFO: Test OK" $_UP_LOG)
  if [[ "$_RESULT_TEST_OK" =~ "INFO: Test OK" ]] ; then
    _DO_NOTHING=YES
  else
    if [ "$silent" = "system" ] ; then
      _DO_NOTHING=YES
    else
      _SEND_ALERT=YES
    fi
  fi
  _RESULT_APT_FAIL=$(grep "Displaying the last 15 lines" $_UP_LOG)
  if [[ "$_RESULT_APT_FAIL" =~ "Displaying the last 15 lines" ]] ; then
    _SEND_ALERT=YES
  fi
  _RESULT_ENJOY=$(grep "Enjoy your Aegir Hosting System" $_UP_LOG)
  if [[ "$_RESULT_ENJOY" =~ "Enjoy your Aegir Hosting System" ]] ; then
    _DO_NOTHING=YES
  else
    _SEND_ALERT=YES
  fi
  _RESULT_ABORTING=$(grep "Aborting" $_UP_LOG)
  if [[ "$_RESULT_ABORTING" =~ "Aborting" ]] ; then
    _SEND_ALERT=YES
  fi
  if [ "$_SEND_ALERT" = "YES" ] ; then
    send_alert
  else
    send_report
  fi
}

up_action ()
{
  if [ -e "/var/backups/BARRACUDA.sh.txt" ] ; then
    if [ -e "/root/.host8.cnf" ] || [[ "$_CHECK_HOST" =~ ".host8." ]] || [ "$_L_VMFAMILY" = "VS" ] ; then
      _DO_NOTHING=YES
    else
      mkdir -p /var/backups/old-firewall-monitor/$_NOW
      mv -f /var/xdrago/monitor/*.log /var/backups/old-firewall-monitor/$_NOW/ &> /dev/null
      rm -f /var/xdrago/monitor/* &> /dev/null
    fi
    sed -i "s/^_AUTOPILOT=NO/_AUTOPILOT=YES/g"             /var/backups/BARRACUDA.sh.txt &> /dev/null
    sed -i "s/^_DNS_SETUP_TEST=YES/_DNS_SETUP_TEST=NO/g"   /var/backups/BARRACUDA.sh.txt &> /dev/null
    sed -i "s/^_SMTP_RELAY_TEST=YES/_SMTP_RELAY_TEST=NO/g" /var/backups/BARRACUDA.sh.txt &> /dev/null
    if [ -e "/root/.host8.cnf" ] || [[ "$_CHECK_HOST" =~ ".host8." ]] || [ "$_L_VMFAMILY" = "VS" ] ; then
      if [[ "$_CHECK_HOST" =~ ".o8.io" ]] ; then
        _DO_NOTHING=YES
      else
        if [ -e "/root/.barracuda.cnf" ] ; then
          sed -i "s/^_AUTOPILOT=.*/_AUTOPILOT=YES/g"                           /root/.barracuda.cnf &> /dev/null
          sed -i "s/^_DNS_SETUP_TEST=.*/_DNS_SETUP_TEST=NO/g"                  /root/.barracuda.cnf &> /dev/null
          sed -i "s/^_SMTP_RELAY_TEST=.*/_SMTP_RELAY_TEST=NO/g"                /root/.barracuda.cnf &> /dev/null
          sed -i "s/^_STRONG_PASSWORDS=.*/_STRONG_PASSWORDS=YES/g"             /root/.barracuda.cnf &> /dev/null
          if [[ "$_CHECK_HOST" =~ ".host8." ]] || [ "$_L_VMFAMILY" = "VS" ] ; then
            sed -i "s/^_MODULES_FIX=.*/_MODULES_FIX=YES/g"                     /root/.barracuda.cnf &> /dev/null
            sed -i "s/^_NGINX_FORWARD_SECRECY=.*/_NGINX_FORWARD_SECRECY=YES/g" /root/.barracuda.cnf &> /dev/null
            sed -i "s/^_NGINX_SPDY=.*/_NGINX_SPDY=YES/g"                       /root/.barracuda.cnf &> /dev/null
            sed -i "s/^_PERMISSIONS_FIX=.*/_PERMISSIONS_FIX=YES/g"             /root/.barracuda.cnf &> /dev/null
            sed -i "s/^_SSH_FROM_SOURCES=.*/_SSH_FROM_SOURCES=YES/g"           /root/.barracuda.cnf &> /dev/null
            sed -i "s/^_REDIS_LISTEN_MODE=.*/_REDIS_LISTEN_MODE=SOCKET/g"      /root/.barracuda.cnf &> /dev/null
          fi
        fi
      fi
      sed -i "s/^_MY_EMAIL=.*/_MY_EMAIL=\"notify\@omega8.cc\"/g"               /root/.barracuda.cnf &> /dev/null
      _THIS_RV=`lsb_release -sc`
      if [ "$_THIS_RV" = "lenny" ] && [ -e "/root/.barracuda.cnf" ] ; then
        sed -i "s/^_LENNY_TO_SQUEEZE=.*/_LENNY_TO_SQUEEZE=YES/g" /var/backups/BARRACUDA.sh.txt &> /dev/null
        sed -i "s/.*_LENNY_TO_SQUEEZE.*//g" /root/.barracuda.cnf &> /dev/null
        sed -i "/^$/d" /root/.barracuda.cnf &> /dev/null
        echo "_LENNY_TO_SQUEEZE=YES" >> /root/.barracuda.cnf
      fi
      if [ -e "/etc/default/tomcat" ] && [ -e "/etc/init.d/tomcat" ] && [ -e "/root/.barracuda.cnf" ] ; then
        sed -i "s/^_TOMCAT_TO_JETTY=.*/_TOMCAT_TO_JETTY=YES/g" /var/backups/BARRACUDA.sh.txt &> /dev/null
        sed -i "s/.*_TOMCAT_TO_JETTY.*//g" /root/.barracuda.cnf &> /dev/null
        sed -i "/^$/d" /root/.barracuda.cnf &> /dev/null
        echo "_TOMCAT_TO_JETTY=YES" >> /root/.barracuda.cnf
      fi
    fi
    if [ -e "/var/backups/BARRACUDA.sh.txt" ] ; then
      if [ "$silent" = "log" ] || [ "$silent" = "system" ] || [ "$silent" = "stock" ] || [ "$silent" = "aegir" ] ; then
        if [ "$silent" = "stock" ] || [ "$silent" = "aegir" ] ; then
          n=8
        else
          if [ "$_L_VMFAMILY" = "VS" ] ; then
            if [ -e "/root/.host8.cnf" ] || [[ "$_CHECK_HOST" =~ ".o8.io" ]] ; then
              n=8
            else
              n=$((RANDOM%800+80))
            fi
          else
            n=8
          fi
        fi
        echo
        echo "Preparing the upgrade in silent mode..."
        echo
        echo "NOTE: There will be no progress displayed in the console"
        echo "but you will receive an e-mail once the upgrade is complete"
        echo
        sleep 5
        echo "You could watch the progress in another window with command:"
        echo "  tail -f $_UP_LOG"
        echo "or wait until you will see the line: BARRACUDA upgrade completed"
        echo
        echo "Waiting $n seconds..."
        sleep $n
        echo "Starting the upgrade in silent mode now..."
        echo
        sed -i "s/^_AUTOPILOT=.*/_AUTOPILOT=YES/g" /root/.barracuda.cnf &> /dev/null
        sed -i "s/^_SPINNER=YES/_SPINNER=NO/g" /var/backups/BARRACUDA.sh.txt &> /dev/null
        if [ "$silent" = "system" ] ; then
          sed -i "s/^_SYSTEM_UPGRADE_ONLY=.*/_SYSTEM_UPGRADE_ONLY=YES/g" /var/backups/BARRACUDA.sh.txt &> /dev/null
          sed -i "s/^_SYSTEM_UPGRADE_ONLY=.*/_SYSTEM_UPGRADE_ONLY=YES/g" /root/.barracuda.cnf &> /dev/null
          sed -i "s/^_AEGIR_UPGRADE_ONLY=.*/_AEGIR_UPGRADE_ONLY=NO/g"    /root/.barracuda.cnf &> /dev/null
          sed -i "s/^_USE_STOCK=.*/_USE_STOCK=NO/g"                      /root/.barracuda.cnf &> /dev/null
        elif [ "$silent" = "stock" ] || [ "$silent" = "aegir" ] ; then
          sed -i "s/^_USE_STOCK=.*/_USE_STOCK=YES/g"                     /var/backups/BARRACUDA.sh.txt &> /dev/null
          sed -i "s/^_USE_STOCK=.*/_USE_STOCK=YES/g"                     /root/.barracuda.cnf &> /dev/null
          sed -i "s/^_SYSTEM_UPGRADE_ONLY=.*/_SYSTEM_UPGRADE_ONLY=NO/g"  /root/.barracuda.cnf &> /dev/null
          if [ "$silent" = "aegir" ] ; then
            sed -i "s/^_AEGIR_UPGRADE_ONLY=.*/_AEGIR_UPGRADE_ONLY=YES/g" /var/backups/BARRACUDA.sh.txt &> /dev/null
            sed -i "s/^_AEGIR_UPGRADE_ONLY=.*/_AEGIR_UPGRADE_ONLY=YES/g" /root/.barracuda.cnf &> /dev/null
          else
            sed -i "s/^_AEGIR_UPGRADE_ONLY=.*/_AEGIR_UPGRADE_ONLY=NO/g"  /root/.barracuda.cnf &> /dev/null
          fi
        elif [ "$silent" = "log" ] ; then
          sed -i "s/^_USE_STOCK=.*/_USE_STOCK=NO/g"                      /root/.barracuda.cnf &> /dev/null
          sed -i "s/^_SYSTEM_UPGRADE_ONLY=.*/_SYSTEM_UPGRADE_ONLY=NO/g"  /root/.barracuda.cnf &> /dev/null
          sed -i "s/^_AEGIR_UPGRADE_ONLY=.*/_AEGIR_UPGRADE_ONLY=NO/g"    /root/.barracuda.cnf &> /dev/null
        fi
        bash /var/backups/BARRACUDA.sh.txt >$_UP_LOG 2>&1
        check_report
      else
        sed -i "s/^_USE_STOCK=.*/_USE_STOCK=NO/g"                        /root/.barracuda.cnf &> /dev/null
        sed -i "s/^_SYSTEM_UPGRADE_ONLY=.*/_SYSTEM_UPGRADE_ONLY=NO/g"    /root/.barracuda.cnf &> /dev/null
        sed -i "s/^_AEGIR_UPGRADE_ONLY=.*/_AEGIR_UPGRADE_ONLY=NO/g"      /root/.barracuda.cnf &> /dev/null
        sed -i "s/^_AUTOPILOT=.*/_AUTOPILOT=NO/g"                        /root/.barracuda.cnf &> /dev/null
        bash /var/backups/BARRACUDA.sh.txt
      fi
    fi
  else
    echo "BARRACUDA.sh.txt installer not available - try again"
    exit 1
  fi
}

up_start ()
{
  if [ -e "/var/run/boa_run.pid" ] ; then
    echo Another BOA installer is running probably - /var/run/boa_run.pid exists
    exit 1
  elif [ -e "/var/run/boa_wait.pid" ] ; then
    echo Some important system task is running probably - /var/run/boa_wait.pid exists
    exit 1
  else
    touch /var/run/boa_run.pid
    touch /var/run/boa_wait.pid
    mkdir -p $_LOG_DIR
    cd /var/backups
    rm -f /var/backups/BARRACUDA.sh*
  fi
  if [ -e "/opt/local/bin/php" ] || [ -e "/opt/local/bin/pear" ] || [ -e "/usr/local/bin/php" ] || [ -e "/usr/local/bin/pear" ] ; then
    rm -f /opt/local/bin/pear
    rm -f /opt/local/bin/php
    rm -f /usr/local/bin/pear
    rm -f /usr/local/bin/php
  fi
  if [ -d "/opt/local/bin" ] ; then
    if [ -x "/opt/php53/bin/php" ] ; then
      ln -s /opt/php53/bin/php /opt/local/bin/php
    elif [ -x "/opt/php54/bin/php" ] ; then
      ln -s /opt/php54/bin/php /opt/local/bin/php
    elif [ -x "/opt/php55/bin/php" ] ; then
      ln -s /opt/php55/bin/php /opt/local/bin/php
    else
      ln -s /opt/php53/bin/php /opt/local/bin/php &> /dev/null
    fi
  fi
}

up_finish ()
{
  rm -f /var/run/boa_run.pid
  rm -f /var/run/boa_wait.pid
  rm -f /var/backups/BARRACUDA.sh*
  rm -f /root/BOA.sh*
  rm -f /root/.bashrc.bak*
  if [ -e "/opt/local/bin/php" ] || [ -e "/usr/local/bin/php" ] ; then
    rm -f /opt/local/bin/php
    rm -f /usr/local/bin/php
  fi
  if [[ "$_CHECK_HOST" =~ ".host8." ]] || [ "$_L_VMFAMILY" = "VS" ] ; then
    service webmin stop &> /dev/null
    service usermin stop &> /dev/null
  fi
  echo
  echo BARRACUDA upgrade completed
  echo Bye
  echo
  if [ "$ifauto" = "auto" ] || [ "$_NEEDS_UPDATE" = "YES" ] ; then
    rm -f /var/backups/BOA.sh.txt-*
    curl -L --max-redirs 10 -k -s --retry 10 --retry-delay 5 -A iCab "http://files.aegir.cc/BOA.sh.txt" -o /var/backups/BOA.sh.txt-$_NOW
    exec bash /var/backups/BOA.sh.txt-$_NOW &> /dev/null
    rm -f /var/backups/BOA.sh.txt-$_NOW
  fi
  exit 0
}

up_stable ()
{
  up_start
  if [ "$silent" = "stock" ] || [ "$silent" = "aegir" ] ; then
    curl -L --max-redirs 10 -k -s --retry 10 --retry-delay 5 -A iCab "https://raw.githubusercontent.com/omega8cc/boa/master/BARRACUDA.sh.txt" -o BARRACUDA.sh.txt
  else
    curl -L --max-redirs 10 -k -s --retry 10 --retry-delay 5 -A iCab "http://files.aegir.cc/versions/stable/txt/BARRACUDA.sh.txt" -o BARRACUDA.sh.txt
  fi
  up_action
  up_finish
}

up_head ()
{
  up_start
  curl -L --max-redirs 10 -k -s --retry 10 --retry-delay 5 -A iCab "https://raw.githubusercontent.com/omega8cc/boa/master/BARRACUDA.sh.txt" -o BARRACUDA.sh.txt
  up_action
  up_finish
}

up_legacy ()
{
  up_start
  curl -L --max-redirs 10 -k -s --retry 10 --retry-delay 5 -A iCab "http://files.aegir.cc/versions/legacy/txt/BARRACUDA.sh.txt" -o BARRACUDA.sh.txt
  up_action
  up_finish
}

set_pin_priority ()
{
  if [ ! -e "/etc/apt/preferences" ] && [ -e "/etc/issue.net" ] ; then
    _THIS_OS=$(grep "Debian" /etc/issue.net)
    if [[ "$_THIS_OS" =~ "Debian" ]] ; then
      _THIS_OS=Debian
    else
      _THIS_OS=Ubuntu
    fi
    if [ "$_THIS_OS" = "Debian" ] ; then
      _THIS_RV=$(grep "6.0" /etc/issue.net)
      if [[ "$_THIS_RV" =~ "6.0" ]] ; then
        curl -L --max-redirs 10 -k -s --retry 10 --retry-delay 5 -A iCab "http://files.aegir.cc/versions/master/aegir/conf/etc-apt-preferences-squeeze.txt" -o /etc/apt/preferences
      else
        curl -L --max-redirs 10 -k -s --retry 10 --retry-delay 5 -A iCab "http://files.aegir.cc/versions/master/aegir/conf/etc-apt-preferences-wheezy.txt" -o /etc/apt/preferences
      fi
    elif [ "$_THIS_OS" = "Ubuntu" ] ; then
      curl -L --max-redirs 10 -k -s --retry 10 --retry-delay 5 -A iCab "http://files.aegir.cc/versions/master/aegir/conf/etc-apt-preferences-ubuntu.txt" -o /etc/apt/preferences
    fi
  fi
  _THIS_DO=$(grep "Ubuntu 12.04" /etc/issue.net)
  if [[ "$_THIS_DO" =~ "Ubuntu 12.04" ]] ; then
    _THIS_DO=YesPrecise
  else
    _THIS_DO=Other
  fi
}

download_wrapper ()
{
  if [ ! -e "$_THIS_FILE" ] ; then
    echo "I can not connect to files.aegir.cc at the moment"
    echo "I will try again in 15 seconds, please wait..."
    sleep 15
    curl -L --max-redirs 10 -k -s --retry 10 --retry-delay 5 -A iCab "http://files.aegir.cc/versions/master/aegir/tools/bin/$(basename "$0")" -o $_THIS_FILE
  fi
}

check_wrapper ()
{
  rm -f /var/backups/$(basename "$0")-now-*
  _THIS_FILE="/var/backups/$(basename "$0")-now-$_NOW"
  curl -L --max-redirs 10 -k -s --retry 10 --retry-delay 5 -A iCab "http://files.aegir.cc/versions/master/aegir/tools/bin/$(basename "$0")" -o $_THIS_FILE
  if [ ! -e "$_THIS_FILE" ] ; then
    download_wrapper
    if [ ! -e "$_THIS_FILE" ] ; then
      download_wrapper
      if [ ! -e "$_THIS_FILE" ] ; then
        download_wrapper
        if [ ! -e "$_THIS_FILE" ] ; then
          echo "Sorry, I gave up."
          echo "Please check http://stats.pingdom.com/x0s6yrbopal6/801243 and try again later."
          exit 1
        fi
      fi
    fi
  fi
  _BIN_FILE="/usr/local/bin/$(basename "$0")"
  _DATE_TEST=$(grep "### $_TODAY ###" $_THIS_FILE)
  if [[ "$_DATE_TEST" =~ "### $_TODAY ###" ]] ; then
    _NEEDS_UPDATE=NO
  else
    _NEEDS_UPDATE=YES
  fi
}

check_dns_curl ()
{
  if [ ! -e "/etc/resolv.conf" ] ; then
    echo "nameserver 8.8.8.8" >/etc/resolv.conf
    echo "nameserver 8.8.4.4" >>/etc/resolv.conf
  else
    _RESOLV_TEST=$(grep "nameserver" /etc/resolv.conf)
    if [[ "$_RESOLV_TEST" =~ "nameserver" ]] ; then
      _DO_NOTHING=YES
    else
      rm -f /etc/resolv.conf
      echo "nameserver 8.8.8.8" >/etc/resolv.conf
      echo "nameserver 8.8.4.4" >>/etc/resolv.conf
    fi
  fi
  _CURL_TEST=$(curl -L --max-redirs 10 -k -s -I "http://files.aegir.cc" 2> /dev/null)
  if [[ "$_CURL_TEST" =~ "200 OK" ]] ; then
    _DO_NOTHING=YES
  else
    apt-get clean -qq &> /dev/null
    apt-get update -qq &> /dev/null
    apt-get install curl -y --force-yes --reinstall &> /dev/null
  fi
}

check_root ()
{
  if [ `whoami` = "root" ] ; then
    chmod a+w /dev/null
    if [ ! -e "/dev/fd" ] ; then
      if [ -e "/proc/self/fd" ] ; then
        rm -rf /dev/fd
        ln -s /proc/self/fd /dev/fd
      fi
    fi
    sed -i "s/.*173.231.133.190.*//g" /etc/hosts
    sed -i "s/^127.0.0.1.*/127.0.0.1 localhost/g" /etc/hosts
    sed -i "/^$/d" /etc/hosts
  else
    echo "ERROR: This script should be ran as a root user - please `sudo -i` first"
    exit 1
  fi
  _DF_TEST=$(df -kTh / -l | grep '/'| sed 's/\%//g'| awk '{print $6}' 2> /dev/null)
  _DF_TEST=${_DF_TEST//[^0-9]/}
  if [ ! -z "$_DF_TEST" ] && [ "$_DF_TEST" -gt "90" ] ; then
    echo "ERROR: Your disk space is almost full - we can not proceed until it is below 90/100"
    exit 1
  fi
}

case "$1" in
  up-stable) cmmand="$1"
             silent="$2"
             ifauto="$3"
             check_root
             check_dns_curl
             check_wrapper
             set_pin_priority
             up_stable
  ;;
  up-head)   cmmand="$1"
             silent="$2"
             ifauto="$3"
             check_root
             check_dns_curl
             check_wrapper
             set_pin_priority
             up_head
  ;;
  up-legacy) cmmand="$1"
             silent="$2"
             ifauto="$3"
             check_root
             check_dns_curl
             check_wrapper
             set_pin_priority
             up_legacy
  ;;
  *)         echo
             echo "Usage: $(basename "$0") {up-stable|up-head|up-legacy} {system|log|stock|aegir}"
             echo
             echo "  Silent Mode Option: system == OS only upgrade"
             echo "  Silent Mode Option: log    == OS and Aegir upgrade"
             echo "  Silent Mode Option: stock  == OS and stock Aegir forced up-head upgrade"
             echo "  Silent Mode Option: aegir  == Only stock Aegir forced up-head upgrade"
             echo
             exit 1
  ;;
esac

