#!/bin/bash


###----------------------------------------###
###
###  Barracuda Aegir Installer
###
###  Copyright (C) 2010-2014 Omega8.cc
###  noc@omega8.cc www.omega8.cc
###
###  This program is free software. You can
###  redistribute it and/or modify it under
###  the terms of the GNU GPL as published by
###  the Free Software Foundation, version 2
###  or later.
###
###  This program is distributed in the hope
###  that it will be useful, but WITHOUT ANY
###  WARRANTY; without even the implied
###  warranty of MERCHANTABILITY or FITNESS
###  FOR A PARTICULAR PURPOSE. See the GNU GPL
###  for more details.
###
###  You should have received a copy of the
###  GNU GPL along with this program.
###  If not, see http://www.gnu.org/licenses/
###
###  Code: https://code.aegir.cc/aegir
###
###----------------------------------------###


###----------------------------------------###
### DON'T EDIT ANYTHING BELOW THIS LINE    ###
###----------------------------------------###

_AEGIR_VERSION=EDIT_AEGIR_VERSION
_BOA_REPO_GIT_URL=EDIT_BOA_REPO_GIT_URL
_BOA_REPO_NAME=EDIT_BOA_REPO_NAME
_DRUSH_CC_REQ=NO
_DRUSH_VERSION=EDIT_DRUSH_VERSION
_PHP_CLI_VERSION=EDIT_PHP_CLI_VERSION
_PHP_FPM_VERSION=EDIT_PHP_FPM_VERSION
_REL_VERSION=`lsb_release -sc`
_STRONG_PASSWORDS=EDIT_STRONG_PASSWORDS
_THIS_DB_HOST=EDIT_THIS_DB_HOST
_USE_STOCK=EDIT_USE_STOCK
_LOCAL_NETWORK_IP=EDIT_LOCAL_NETWORK_IP
_ROOT="$HOME"
#
if [ "$_PHP_CLI_VERSION" = "5.5" ] && [ -x "/opt/php55/bin/php" ] ; then
  _L_PHP_CLI=/opt/php55/bin
elif [ "$_PHP_CLI_VERSION" = "5.4" ] && [ -x "/opt/php54/bin/php" ] ; then
  _L_PHP_CLI=/opt/php54/bin
elif [ "$_PHP_CLI_VERSION" = "5.3" ] && [ -x "/opt/php53/bin/php" ] ; then
  _L_PHP_CLI=/opt/php53/bin
elif [ "$_PHP_CLI_VERSION" = "5.2" ] && [ -x "/opt/php52/bin/php" ] ; then
  _L_PHP_CLI=/opt/php52/bin
fi
_DRUSHCMD="$_L_PHP_CLI/php $_ROOT/drush/drush.php"
#
SHELL=/bin/bash
PATH=$_L_PHP_CLI:/usr/local/bin:/usr/local/sbin:/opt/local/bin:/usr/bin:/usr/sbin:/bin:/sbin

###---### Functions.
#
# Noticeable messages.
msg () {
  echo "Barracuda [`date`] ==> $*"
}
#
# Update local INI for PHP CLI on the Aegir Master Instance.
update_php_cli_local_ini () {
  _U_HD="/var/aegir/.drush"
  _U_TP="/var/aegir/.tmp"
  _PHP_CLI_UPDATE=NO
  _CHECK_USE_PHP_CLI=`grep "/opt/php" $_DRUSH_FILE`
  _PHP_V="55 54 53 52"
  for e in $_PHP_V; do
    if [[ "$_CHECK_USE_PHP_CLI" =~ "php${e}" ]] && [ ! -e "$_U_HD/.ctrl.php${e}.txt" ] ; then
      _PHP_CLI_UPDATE=YES
    fi
  done
  if [ "$_PHP_CLI_UPDATE" = "YES" ] || [ ! -e "$_U_HD/php.ini" ] || [ ! -d "$_U_TP" ] || [ ! -e "$_U_HD/.ctrl.eq.txt" ] ; then
    rm -f -r $_U_TP
    mkdir -p $_U_TP
    chmod 700 $_U_TP
    mkdir -p $_U_HD
    rm -f $_U_HD/.ctrl.php*
    rm -f $_U_HD/php.ini
    if [[ "$_CHECK_USE_PHP_CLI" =~ "php55" ]] ; then
      cp -af /opt/php55/lib/php.ini $_U_HD/php.ini
      _U_INI=55
    elif [[ "$_CHECK_USE_PHP_CLI" =~ "php54" ]] ; then
      cp -af /opt/php54/lib/php.ini $_U_HD/php.ini
      _U_INI=54
    elif [[ "$_CHECK_USE_PHP_CLI" =~ "php53" ]] ; then
      cp -af /opt/php53/lib/php.ini $_U_HD/php.ini
      _U_INI=53
    elif [[ "$_CHECK_USE_PHP_CLI" =~ "php52" ]] ; then
      cp -af /opt/php52/lib/php.ini $_U_HD/php.ini
      _U_INI=52
    fi
    if [ -e "$_U_HD/php.ini" ] ; then
      _INI="open_basedir = \".:/var/aegir:/data/all:/data/disk/all:/data/conf:/usr/bin:/opt/tools/drush:/tmp:/opt/tika:/opt/tika7:/opt/tika8:/opt/tika9:/opt/php52:/opt/php53:/opt/php54:/opt/php55\""
      _INI=${_INI//\//\\\/}
      _QTP=${_U_TP//\//\\\/}
      sed -i "s/.*open_basedir =.*/$_INI/g"                              $_U_HD/php.ini &> /dev/null
      sed -i "s/.*error_reporting =.*/error_reporting = 1/g"             $_U_HD/php.ini &> /dev/null
      sed -i "s/.*session.save_path =.*/session.save_path = $_QTP/g"     $_U_HD/php.ini &> /dev/null
      sed -i "s/.*soap.wsdl_cache_dir =.*/soap.wsdl_cache_dir = $_QTP/g" $_U_HD/php.ini &> /dev/null
      sed -i "s/.*sys_temp_dir =.*/sys_temp_dir = $_QTP/g"               $_U_HD/php.ini &> /dev/null
      sed -i "s/.*upload_tmp_dir =.*/upload_tmp_dir = $_QTP/g"           $_U_HD/php.ini &> /dev/null
      echo > $_U_HD/.ctrl.php${_U_INI}.txt
      echo > $_U_HD/.ctrl.eq.txt
    fi
  fi
}
#
# Update php-cli for Drush.
update_php_cli_drush () {
  _DRUSH_FILE="$_ROOT/drush/drush.php"
  if [ "$_PHP_CLI_VERSION" = "5.5" ] && [ -x "/opt/php55/bin/php" ] ; then
    sed -i "s/^#\!\/.*/#\!\/opt\/php55\/bin\/php/g"  $_DRUSH_FILE &> /dev/null
  elif [ "$_PHP_CLI_VERSION" = "5.4" ] && [ -x "/opt/php54/bin/php" ] ; then
    sed -i "s/^#\!\/.*/#\!\/opt\/php54\/bin\/php/g"  $_DRUSH_FILE &> /dev/null
  elif [ "$_PHP_CLI_VERSION" = "5.3" ] && [ -x "/opt/php53/bin/php" ] ; then
    sed -i "s/^#\!\/.*/#\!\/opt\/php53\/bin\/php/g"  $_DRUSH_FILE &> /dev/null
  elif [ "$_PHP_CLI_VERSION" = "5.2" ] && [ -x "/opt/php52/bin/php" ] ; then
    sed -i "s/^#\!\/.*/#\!\/opt\/php52\/bin\/php/g"  $_DRUSH_FILE &> /dev/null
  else
    msg "FATAL ERROR: _PHP_CLI_VERSION must be set to one of supported values"
    msg "FATAL ERROR: Aborting AegirSetupM installer NOW!"
    touch /opt/tmp/status-AegirSetupM-FAIL
    exit 1
  fi
}
#
# Extract archive.
extract_archive () {
  if [ ! -z $1 ] ; then
    case $1 in
      *.tar.bz2)   tar xjf $1    ;;
      *.tar.gz)    tar xzf $1    ;;
      *.bz2)       bunzip2 $1    ;;
      *.rar)       unrar x $1    ;;
      *.gz)        gunzip -q $1  ;;
      *.tar)       tar xf $1     ;;
      *.tbz2)      tar xjf $1    ;;
      *.tgz)       tar xzf $1    ;;
      *.zip)       unzip -qq $1  ;;
      *.Z)         uncompress $1 ;;
      *.7z)        7z x $1       ;;
      *)           echo "'$1' cannot be extracted via >extract<" ;;
    esac
    rm -f $1
  fi
}
#
# Download and extract from dev.
get_dev_ext () {
  if [ ! -z $1 ] ; then
    curl -L --max-redirs 10 -k -s -O --retry 10 --retry-delay 15 -A iCab "http://files.aegir.cc/dev/$_AEGIR_VERSION/$1"
    extract_archive "$1"
  fi
}
#
# Remove dangerous stuff from the string.
sanitize_string () {
  echo "$1" | sed 's/[\\\/\^\?\>\`\#\"\{\(\$\@\&\|\*]//g; s/\(['"'"'\]\)//g'
}

###--------------------###

if [ `whoami` = "root" ] ; then
  msg "FATAL ERROR: This script should be ran as a non-root user"
  msg "FATAL ERROR: Aborting AegirSetupM installer NOW!"
  touch /opt/tmp/status-AegirSetupM-FAIL
  exit 1
fi

_AEGIR_HOST=`uname -n`
_RESOLVEIP=`echo $(getent ahostsv4 $_AEGIR_HOST) | cut -d: -f2 | awk '{ print $1}' 2> /dev/null`

if [ -z "$_RESOLVEIP" ] ; then
  msg "FATAL ERROR: This server does not have a hostname that resolves to an IP address"
  msg "FATAL ERROR: Aborting AegirSetupM installer NOW!"
  touch /opt/tmp/status-AegirSetupM-FAIL
  exit 1
else
  _AEGIR_HOST_IP="$_RESOLVEIP"
fi

_MYSQLTEST=`mysql -h$_AEGIR_HOST_IP  -uINVALIDLOGIN  -pINVALIDPASS 2>&1 >/dev/null | cat`

if [ -z `echo $_MYSQLTEST | grep -q "ERROR \(2003\|1130\)"` ] ; then
  msg  "MySQL is listening on $_AEGIR_HOST_IP."
  _DO_NOTHING=YES
else
  msg "FATAL ERROR: MySQL is not configured to listen on $_AEGIR_HOST_IP"
  msg "FATAL ERROR: Aborting AegirSetupM installer NOW!"
  touch /opt/tmp/status-AegirSetupM-FAIL
  exit 1
fi

msg "INFO: Barracuda will now generate a mysql super user password for you: "

_AEGIR_DB_USER=aegir_root
_ESC_APASS=""
_LEN_APASS=0

if [ "$_STRONG_PASSWORDS" = "YES" ] ; then
  _ESC_APASS=$(randpass 32 esc)
  _ESC_APASS=`echo -n $_ESC_APASS | tr -d "\n"`
  _LEN_APASS=$(echo ${#_ESC_APASS})
fi

if [ -z "$_ESC_APASS" ] || [ $_LEN_APASS -lt 19 ] ; then
  _ESC_APASS=`pwgen -v -s -1`
  _ESC_APASS=`echo -n $_ESC_APASS | tr -d "\n"`
  _ESC_APASS=`sanitize_string "$_ESC_APASS"`
fi

cat <<EOF
  Username : $_AEGIR_DB_USER
  Password : $_ESC_APASS
  Hostname : $_AEGIR_HOST ($_AEGIR_HOST_IP)
EOF

_ESC="\`%\`.*"
mysql -uroot mysql<<EOFMYSQL
GRANT ALL PRIVILEGES ON $_ESC TO '$_AEGIR_DB_USER'@'$_AEGIR_HOST' IDENTIFIED BY '$_ESC_APASS' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON $_ESC TO '$_AEGIR_DB_USER'@'$_AEGIR_HOST_IP' IDENTIFIED BY '$_ESC_APASS' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON $_ESC TO '$_AEGIR_DB_USER'@'localhost' IDENTIFIED BY '$_ESC_APASS' WITH GRANT OPTION;
EOFMYSQL

msg "INFO: Installing drush in $_ROOT"
cd $_ROOT
get_dev_ext "drush-$_DRUSH_VERSION.tar.gz"
find $_ROOT/drush -type d -exec chmod 0755 {} \; &> /dev/null
find $_ROOT/drush -type f -exec chmod 0644 {} \; &> /dev/null
chmod 755 $_ROOT/drush/drush
chmod 755 $_ROOT/drush/drush.php
if [ "$_DRUSH_VERSION" = "mini-4-14-03-2014" ] ; then
  _DRUSH_CC_REQ=NO
else
  _DRUSH_CC_REQ=YES
fi

update_php_cli_drush
update_php_cli_local_ini

if $_DRUSHCMD help > /dev/null ; then
  msg "INFO: Drush seems to be functioning properly"
else
  msg "FATAL ERROR: Drush is broken ($_DRUSH help failed)"
  msg "FATAL ERROR: Aborting AegirSetupM installer NOW!"
  touch /opt/tmp/status-AegirSetupM-FAIL
  exit 1
fi

if $_DRUSHCMD help | grep "^ provision-install" > /dev/null ; then
  msg "INFO: Provision already seems to be installed"
else
  msg "INFO: Installing provision backend in $_ROOT/.drush"
  mkdir -p $_ROOT/.drush/{sys,xts,usr}
  if [ "$_AEGIR_VERSION" = "HEAD" ] ; then
    cd $_ROOT/.drush
    if [ "$_USE_STOCK" = "YES" ] ; then
      git clone --branch 6.x-2.x-stock-revert git://github.com/omega8cc/provision.git $_ROOT/.drush/sys/provision &> /dev/null
    else
      if [ "$_BOA_REPO_NAME" = "barracuda" ] || [ "$_BOA_REPO_NAME" = "octopus" ] ; then
        _BOA_REPO_GIT_URL_LOCAL="http://git.drupal.org/sandbox/omega8cc"
        git clone $_BOA_REPO_GIT_URL_LOCAL/1074910.git $_ROOT/.drush/sys/provision &> /dev/null
        _BOA_REPO_GIT_URL_Q=${_BOA_REPO_GIT_URL_LOCAL//\//\\\/}
        sed -i "s/MAKEFILE_REPO_GIT_URL/$_BOA_REPO_GIT_URL_Q/g" $_ROOT/.drush/sys/provision/aegir.make &> /dev/null
        sed -i "s/hostmaster.git/1074912.git/g" $_ROOT/.drush/sys/provision/aegir.make &> /dev/null
      else
        git clone $_BOA_REPO_GIT_URL/provision.git $_ROOT/.drush/sys/provision &> /dev/null
        _BOA_REPO_GIT_URL_Q=${_BOA_REPO_GIT_URL//\//\\\/}
        sed -i "s/MAKEFILE_REPO_GIT_URL/$_BOA_REPO_GIT_URL_Q/g" $_ROOT/.drush/sys/provision/aegir.make &> /dev/null
      fi
    fi
    msg "INFO: Downloading Drush and Provision extensions..."
    git clone --branch 6.x-2.x git://github.com/omega8cc/provision_cdn.git $_ROOT/.drush/xts/provision_cdn       &> /dev/null
    git clone --branch 7.x-1.x git://github.com/omega8cc/drush_ecl.git $_ROOT/.drush/usr/drush_ecl               &> /dev/null
    git clone --branch 7.x-2.x git://github.com/omega8cc/registry_rebuild.git $_ROOT/.drush/usr/registry_rebuild &> /dev/null
    git clone --branch 7.x-1.x git://github.com/omega8cc/security_review.git $_ROOT/.drush/xts/security_review   &> /dev/null
    git clone --branch 7.x-2.x git://github.com/omega8cc/provision_boost.git $_ROOT/.drush/xts/provision_boost   &> /dev/null
    rm -f -r $_ROOT/.drush/*/.git
    rm -f -r $_ROOT/.drush/*/*/.git
    cd $_ROOT/.drush/usr
    get_dev_ext "clean_missing_modules.tar.gz"
  else
    cd $_ROOT/.drush/sys
    curl -L --max-redirs 10 -k -s --retry 10 --retry-delay 15 -A iCab "http://files.aegir.cc/versions/stable/tar/provision-$_AEGIR_VERSION.tar.gz" | tar -xzf -
    msg "INFO: Downloading Drush and Provision extensions..."
    cd $_ROOT/.drush/usr
    get_dev_ext "clean_missing_modules.tar.gz"
    get_dev_ext "drush_ecl.tar.gz"
    get_dev_ext "registry_rebuild.tar.gz"
    cd $_ROOT/.drush/xts
    get_dev_ext "provision_boost.tar.gz"
    get_dev_ext "provision_cdn.tar.gz"
    get_dev_ext "security_review.tar.gz"
  fi
fi
sed -i "s/drush_log(t('Contrib latestDir/drush_log(dt('Contrib latestDir/g" $_ROOT/.drush/sys/provision/platform/verify.provision.inc &> /dev/null

msg "INFO: Installing the frontend"
if [ "$_USE_STOCK" = "YES" ] || [ "$_DRUSH_CC_REQ" = "YES" ] ; then
  $_DRUSHCMD cache-clear drush >$_ROOT/install.log 2>&1
fi
_HOSTMASTER_ROOT="$_ROOT/hostmaster-$_AEGIR_VERSION"
$_DRUSHCMD hostmaster-install --aegir_host=$_AEGIR_HOST --aegir_db_user=$_AEGIR_DB_USER --aegir_db_pass=$_ESC_APASS --aegir_root=$_ROOT --root=$_HOSTMASTER_ROOT --version=$_AEGIR_VERSION $@

mkdir -p /var/aegir/backups/system
chmod 700 /var/aegir/backups/system
_L_SYS="/var/aegir/backups/system/.$_AEGIR_DB_USER.pass.txt"
echo "$_ESC_APASS" > $_L_SYS
chmod 0600 $_L_SYS

###----------------------------------------###
###
###  Barracuda Aegir Installer
###  Copyright (C) 2010-2014 Omega8.cc
###  noc@omega8.cc www.omega8.cc
###
###----------------------------------------###
