#!/bin/bash
source /etc/profile
_options=${@};
_centos_release=$(/bin/rpm --eval='%centos_ver')

if [[ -e /opt/eig_linux/etc/account_pl.yaml ]]; then
    account_pl=$(grep -oP '(?<=^server_class: )\S+' /opt/eig_linux/etc/account_pl.yaml);
    if [[ ${account_pl} == "reseller" ]]; then
        _reseller=1;
    elif [[ ${account_pl} == "shared" || ${account_pl} == "shared_pro" ]]; then
        _reseller=0;
    else
        echo "cannot determine if reseller or shared" >&2
        exit 1;
    fi;
else
    echo "cannot find /opt/eig_linux/etc/account_pl.yaml" >&2
    exit 1;
fi;

#if [[ ${HOSTNAME} =~ \.websitewelcome\.com$ ]]; then
#    _reseller=1;
#elif [[ ${HOSTNAME} =~ \.hostgator\.com$ ]]; then
#    _reseller=0;
#fi

if [[ -f /etc/cpanel/ea4/is_ea4 ]] && rpm -q --quiet ea-cpanel-tools; then
    _ea4=1;
else
    _ea4=0;
fi;

while getopts ":h:t:dn:" opt; do
  case $opt in
    t)
      if [[ $OPTARG =~ ^(disable_services|pre_boot|post_boot|gen_ifcfg_eth0|disk_clean|disk_reservation)$ ]]; then
        _task=$OPTARG
        echo "-t was triggered, Parameter: $OPTARG" >&2
      else
        echo "Invalid task: -$OPTARG" >&2
        exit 1
      fi
      ;;
    h)
      if [[ $OPTARG =~ ^(old|new)$ ]]; then
        _host=$OPTARG
        echo "-h was triggered, Parameter: $OPTARG" >&2
      else
        echo "Invalid Host: $OPTARG" >&2
        exit 1
      fi
      ;;
    d)
      echo "-d was triggered" >&2
      _disable=1
      ;;
    n)
      _num_homes=$OPTARG
      echo "-n was triggered, Parameter: $OPTARG" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      echo "Usage: ${0} [-d] [-h HOST] [-t TASK]" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done
shift $((OPTIND-1))

disk_clean () {
    if [[ "${_host}" == "old" ]]; then
        echo "$(date) :: disk_clean: "
        find /home*/*/.spamassassin -name '*broken*' -size +100M -ls -delete
        montool diskclean -a -p 70 --force || exit 1;
        find /var/cpanel/bandwidth/ -type f ! -name \*.sqlite -exec rm -vf {} \;
	find /var/cpanel/php/sessions/ -type f -mtime +1 -delete
    fi;
}

fix_links () {
  find /var/lib/mysql -maxdepth 1 -type l | while read _link; do
    _link_target=$(readlink -f ${_link});
    _link_user=$(echo ${_link_target}|awk -F\/ '/^\/home[0-5]?\//{print $3}');
    if id ${_link_user:-LOLNO} &> /dev/null && [[ ! -e ${_link_target} ]]; then
      if [[ ${_num_homes} ]]; then
          unset homes;
          for i in $(eval echo {1..${_num_homes}} ); do
              homes+=("home${i}");
          done;
      elif [[ ${_reseller} == 1 ]]; then
          homes=( home1 home2 )
      else
          homes=( home5 )
      fi
      for home in ${homes[@]};do
        if [[ -d /${home} ]]; then
          _link_new_target=${_link_target//\/home\//\/${home}\/};
          _link_new_target=${_link_new_target//\/home[0-4]\//\/${home}\/};
          echo "$(date) :: fix_links: link_user=${_link_user} home=${home} link=${_link} link_target=${_link_target} new_link_target=${_link_new_target}"
          if [[ -e ${_link_new_target} ]]; then
            ln -vsf ${_link_new_target} ${_link};
            break
          fi;
        fi;
      done
    fi;
  done;
}

fix_link_perms () {
  find /var/lib/mysql -maxdepth 1 -type l | while read _link; do
    _link_target=$(readlink -f ${_link});
    echo "$(date) :: fix_link_perms: link=${_link} link_target=${_link_target}"
    if [[ -e ${_link_target} ]]; then
      find ${_link_target} -type d ! -perm 0700 -exec chmod -v 0700 {} \+;
      find ${_link_target} -type f ! -perm 0660 -exec chmod -v 0660 {} \+;
    fi;
  done;
}

fix_homes () {
  if [ "${_host}" == 'new' ]; then
    if [[ ${_num_homes} ]]; then
      unset homes;
      for i in $(eval echo {1..${_num_homes}} ); do
        homes+=("home${i}");
      done;
    elif [[ ${_reseller} == 1 ]]; then
        homes=( home1 home2 )
    else
        homes=( home5 )
    fi
    if [[ ${#homes[@]} -lt 4 ]]; then
      sed -i 's#/home/#/home9/#' /etc/passwd;
    fi;
    /etc/init.d/hgstartprovo start
    for home in ${homes[@]};do
      if [[ -d /${home} ]]; then
        for _user in $(/bin/ls /${home}); do
          if id ${_user} &> /dev/null; then
            _homedir=$(getent passwd ${_user} | awk -F: '{print $6}')
            if [ ! -z "${_homedir}" ]; then
              echo "$(date) :: fix_homes: user=${_user} home=${home}"
              sed -i "s/^HOMEDIRPATHS=.*/HOMEDIRPATHS=\/${home}\/${_user}/" /var/cpanel/users/${_user}
              sed -i "s/\/home[1-9]*\/${_user}/\/${home}\/${_user}/g" /var/cpanel/userdata/${_user:-lolno}/*
              usermod -d /${home}/${_user} ${_user}
            fi
          fi
        done
      fi
    done
    fix_links;
    fix_link_perms;
  else
    echo "Failed: Cannot run fix_homes on ${_host} host"
    exit 1
  fi
}

fix_systemd () {
  if ! id polkitd &> /dev/null; then
    yum reinstall polkit* systemd* trousers -y
    for user in root bin daemon adm; do
      usermod -G ${user} ${user};
    done
    userdel logcheck
    groupadd -r nohidepid
    usermod -a -G nohidepid polkitd
    usermod -a -G nohidepid zabbix
  fi
}

pre_boot () {
  echo "$(date) :: pre_boot: starting"
  if [ "${_host}" == 'new' ]; then
    rm /etc/cron.d/mig_presync;
    mv /etc/profile.d/less.sh{,.bak}
    if [[ -f /root/.server_migration/min_uid ]]; then
      _min_uid_src=$(cat /root/.server_migration/min_uid)
      _min_uid_dst=$(awk '$1 == "UID_MIN" {print $2}' /etc/login.defs)
      if [[ ( ${_min_uid_src} -gt 0 && ${_min_uid_dst} -gt 0 ) && ( ${_min_uid_src} -ne ${_min_uid_dst} ) ]]; then
        sed -i "s#^UID_MIN .*#UID_MIN ${_min_uid_src}#" /etc/login.defs
        sed -i "s#^GID_MIN .*#GID_MIN ${_min_uid_src}#" /etc/login.defs
      fi
    fi
    sed -i "s#ETHDEV.*#ETHDEV $(ip route show default 0.0.0.0/0 | grep -Po '(?<=dev )\S+')#" /etc/wwwacct.conf
    _homes=$(grep -cP '/home\d' /etc/fstab)
    sed -i "s#HOMEMATCH .*#HOMEMATCH home[1-${_homes}]#" /etc/wwwacct.conf
    if [ "${_centos_release}" -eq 7 ]; then
      fix_systemd
    fi
    if [[ ! -f /root/.server_migration/skip_homes ]]; then
      fix_homes
    fi
    for service in eigeximlogd gatordovelogintrackd gatorftpwatch gatorlogintrackd nxlog; do
        chkconfig $service on
    done
    chmod -v 755 /usr/sbin/mysqld
    umount /var/mysqltmp
    mount /var/mysqltmp
    if [ "${_centos_release}" -eq 7 ]; then
      chown -v mysql. /var/run/mysqld
      service mysqld start || exit 1
      export HOSTNAME=$(awk '$1 == "HOST" {print $2}' /etc/wwwacct.conf)
      /usr/bin/hostnamectl set-hostname ${HOSTNAME} 
    else
      service mysql start || exit 1
      source /etc/sysconfig/network
      /bin/hostname ${HOSTNAME}
    fi
    mysql_upgrade -s && touch /etc/eig_mysql_upgrade
    puppet agent --enable
    rm -vf /var/cpanel/sysinfo.config
    find /var/cpanel/ -name \*.cache -type f -delete -print
    /scripts/upcp --sync
    sed -i "/$(hostname -i)/d" /etc/hosts
    echo '@reboot root source /etc/profile; bash /root/.server_migration/migration_tasks -h new -t post_boot &> /dev/null' > /etc/cron.d/post_mig_update
    mv -f /root/.server_migration/ifcfg-eth0 /etc/sysconfig/network-scripts/
    while [[ -f /var/lib/puppet/state/agent_catalog_run.lock ]]; do
      echo "$(hostname) puppet currently running. Waiting for run to complete" &> /dev/null
      sleep 2
    done;
    perl /opt/hgmods/multi_shared.pl
    /scripts/rebuildhttpdconf
    chgrp -v mailtrap /usr/sbin/sendmail
    chmod -v 2755 /usr/sbin/sendmail
    chown -Rv zabbix. /etc/zabbix/ /var/run/zabbix
    sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config
    if [[ -d /opt/php54 ]]; then
        cat > /usr/local/apache/conf/includes/hgincludes/phpcur.conf <<-PHPCUR
	AddType application/x-httpd-phpcur .php54
	<Directory />
	    suPHP_AddHandler application/x-httpd-phpcur
	</Directory>
	PHPCUR
    fi
    /root/bin/rebuild_http_suspension
    sed -i 's/^###\(.*\)/\1/' /var/spool/cron/root
    rm -vfr /var/cpanel/configs.cache/*
    rm -vf /opt/eig_linux/etc/puppetfeatures/clamd_disable
  elif [ "${_host}" == 'old' ]; then
    mv -v /etc/ips{,.migrated}
    export _dev=$(ip route show default 0.0.0.0/0 | grep -Po '(?<=dev )\S+')
    sed -i -r '/(GATEWAY|IPADDR|NETMASK)/d' /etc/sysconfig/network-scripts/ifcfg-${_dev}
    rm -vf /etc/sysconfig/network-scripts/route-eth0.106
    service network stop;
    sleep 900;
    service network start;
    new_ip=$(grep -oP '(?<=IPADDR=").*?(?=")' /etc/sysconfig/network-scripts/ifcfg-${_dev});
    for counter in {1..10}; do
      sleep 2;
      arping -c 2 -U ${new_ip};
    done;
    _is_virtual=$(/usr/bin/facter is_virtual)
    if [ "${_is_virtual}" == 'true' ]; then
      shutdown -h now
    fi 
  fi
  echo "$(date) :: pre_boot: finished"
}

post_boot () {
  echo "$(date) :: post_boot: starting"
  if [ "${_host}" == 'new' ]; then
    awk -F: '{print $1}' /etc/ips | xargs -n 1 -P 8 arping -c 2 -U
    awk -F: '{print $1}' /etc/ips | xargs -n 1 -P 8 arping -c 2 -U
    rm -vf "/root/.mig-${HOSTNAME}"
    rm -vf /etc/cron.d/post_mig_update
    echo $(dig +short ${HOSTNAME}) > /var/cpanel/mainip
    sed -i "/${HOSTNAME//.*}/d" /etc/hosts
    /usr/local/cpanel/scripts/fixetchosts
    /scripts/rebuildhttpdconf
    awk -F: '{print $1}' /etc/ips | xargs -n 1 -P 8 arping -c 2 -U
    awk -F: '{print $1}' /etc/ips | xargs -n 1 -P 8 arping -c 2 -U
    if [[ ${_ea4} == 0 ]] && ! rpm -q --quiet eig-php-selector; then
        yum -y install eig-php-selector
    fi;
    /scripts/removeacct eig1wp11 --force
    rpm eig-site247-wp && yum remove -y eig-site247-wp;
    yum install -y eig-site247-wp procmail psacct
    mkdir -vp /usr/local/cpanel/3rdparty/basekit/pm
    yum -y --enablerepo=hgrepo-testing install basekit-pl-unbranded perl-B-C perl-MIME-Base64-Perl
    puppet agent -t
    if [[ -f /usr/local/cpanel/3rdparty/basekit/pm/BaseKit.pm ]]; then
      ln -vs /usr/local/cpanel/3rdparty/basekit/pm/BaseKit.pm /usr/local/cpanel/Cpanel/BaseKit.pm
      if [[ -d /usr/local/cpanel/base/frontend/hostgator/basekit_sb ]]; then
        rmdir /usr/local/cpanel/base/frontend/hostgator/basekit_sb;
      fi
      ln -sv /usr/local/cpanel/3rdparty/basekit/client /usr/local/cpanel/base/frontend/hostgator/basekit_sb;
    fi
    service zabbix-agent restart
    if [[ ${HOSTNAME} =~ \.(br|cl|co|es|la|mx)$ && ! ${HOSTNAME} =~ ^wp[0-9]+\. ]]; then
        bash <(curl -ks https://git.hostgator.com.br/monitoramento/install_softaculous/raw/master/install.sh);
        curl -s https://git.hostgator.com.br/monitoramento/install_softaculous/raw/master/iscripts.php > /usr/local/cpanel/whostmgr/docroot/cgi/softaculous/enduser/iscripts.php;
        puppet agent -t;
    fi;
    if [[ -s /root/.server_migration/skipped_users ]]; then
        for skipped_user in $(cat /root/.server_migration/skipped_users); do
            if id -u ${skipped_user:-LOLNONONO} &>/dev/null && [[ ! -d /home/${skipped_user:-LOLNONONO} ]]; then
                /scripts/removeacct ${skipped_user:-LOLNONONO} --force
            fi
        done                
    fi
    if [[ -f /opt/eig_linux/etc/puppetfeatures/datacycle ]]; then
      /root/bin/backuphelper setup
    fi
    /opt/eig_linux/bin/hostinfo
    /scripts/fixquotas &> /dev/null
    if [[ -f '/etc/eig_mysql_upgrade' ]]; then
      mysql_upgrade --force
      rm -vf /etc/eig_mysql_upgrade
      service mysql restart
    fi
    rm -vf "$0"
  else
    echo "Failed: Cannot run ${_task} on ${_host} host"
    exit 1
  fi
  echo "$(date) :: post_boot: finished"
}

disable_services () {
  puppet agent --disable 'Server Migration in progress'
  if [ "${_centos_release}" -eq 7 ]; then
  _services=(cpanel crond atd zabbix-agent dovecot httpd pure-ftpd exim sshd_client mysqld clamd@scan.service monit)
else
  _services=(cpanel crond atd zabbix-agent dovecot httpd pure-ftpd exim sshd_client mysql clamd.scan monit)
fi
  for service in ${_services[@]}; do
    echo "$(date) :: disable_services: stopping: ${service}"
    service ${service} stop
  done
  killall -9 httpd php php-cgi
  chmod -v 0 /scripts/restartsrv*
  
  if [ "${_host}" == 'old' ]; then
    if [ -n "${_disable+x}" ]; then
      if [[ -e /root/.server_migration/motd.old_post ]]; then
        \cp -vf /root/.server_migration/motd.old_post /root/.motd
      fi
#      if [[ -f /usr/share/nginx/html/503-upgrade.html && -f /etc/nginx/nginx.conf ]]; then
          echo "setting up maintenance page"
          #\cp -fv /root/.server_migration/nginx.conf /etc/nginx/nginx.conf
          #sed -i "s/::HOSTNAME::/${HOSTNAME}/g" /etc/nginx/nginx.conf
          #chattr -V +i /etc/nginx/nginx.conf
          #service nginx reload
	  yum install -y --disablerepo='*' --enablerepo=hgrepo thttpd
	  cd /opt/thttpd/htdocs/
	  ln -svf upgrade.html index.html
	  service thttpd start
#      fi;
     if [ "${_centos_release}" -eq 7 ]; then
      for service in ${_services[@]}; do
       echo "disable c7 service: ${service}"
       systemctl disable ${service};
      done
     else
      for service in ${_services[@]}; do
        echo "disable c6 service: ${service}"
        chmod -v 0 /etc/init.d/${service}
        chattr -V +i /etc/init.d/${service}
      done
     fi
    fi
  elif [ "${_host}" == 'new' ]; then
    if [[ -e /root/.migration_key ]]; then
        touch /root/.migration_key
    fi
    for service in eigeximlogd gatordovelogintrackd gatorftpwatch gatorlogintrackd nxlog; do 
        service $service stop
        chkconfig $service off
    done
    for filename in /etc/passwd /etc/group /etc/shadow /etc/gshadow; do
      sed -i -r '/^(cpanel|cpses|zabbix|nginx|mysql|mailman)/d' ${filename}
    done
    chmod -v 0 /usr/sbin/mysqld
    touch /opt/eig_linux/etc/puppetfeatures/clamd_disable
  fi
}

gen_ifcfg_eth0 () {
  if [ "${_host}" == 'old' ]; then
    echo "$(date) :: gen_ifcfg_eth0"
    export _dev=$(ip route show default 0.0.0.0/0 | grep -Po '(?<=dev )\S+')
    read -r _ip _prefix <<<$(ip -4 -o add show ${_dev} label ${_dev}|awk -F'[[:space:]/]+' '{print $4,$5}')
    _gateway=$(ip route list 0/0 | /usr/bin/awk {'print $3'})

    _ifcg=/root/.server_migration/ifcfg-eth0
    cat > "${_ifcg}" <<-ICFG_EOF
	DEVICE=eth0
	BOOTPROTO=static
	ONBOOT=yes
	TYPE=Ethernet
	IPV6INIT=no
	IPADDR=${_ip}
	PREFIX=${_prefix}
	GATEWAY=${_gateway}
	ICFG_EOF
  else
    echo "Failed: Cannot run ${_task} on ${_host} host"
    exit 1
  fi
}

disk_reservation () {
  if [[ "${_host}" == 'new' ]]; then
    for hh in /home[1-5]; do
      echo "$(date) :: disk_reservation: hh=${hh}"
      findmnt -noSOURCE -T${hh} | xargs -n1 tune2fs -m0;
    done
  fi
}

exec >>/root/.server_migration/migration_tasks.log 2>&1;
echo "--------vvv-------vvv=--------vvv--------";
echo "-- Started: $(date)    ::    Args: ${_options}";
${_task}
echo "-- Completed: $(date)    ::    Args: ${_options}";
echo "--------^^^--------^^^--------^^^--------";
echo;
