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

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;
    else
        _reseller=0;
    fi;
else
    echo "cannot find /opt/eig_linux/etc/account_pl.yaml" >&2
    exit 1;
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:m:" opt; do
  case $opt in
    t)
      if [[ $OPTARG =~ ^(disable_services|prepare|pre_boot|post_boot|gen_ifcfg_eth0|disk_clean|disk_reservation|gen_nm_eth0|enable_services)$ ]]; 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
      ;;
    m)
      if [[ $OPTARG =~ ^(remote|in_place)$ ]]; then
        _mig_type=$OPTARG
        echo "-m was triggered, Parameter: $OPTARG" >&2
      else
        echo "Invalid migration type: $OPTARG" >&2
        exit 1
      fi
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      echo "Usage: ${0} [-d] [-h HOST] [-t TASK] [-m MIGRATION TYPE (remote/in_place)]" >&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
    /etc/init.d/hgstartprovo start
    for home in ${homes[@]};do
      if [[ -d /${home} ]]; then
        for _user in $(find /${home} -mindepth 1 -maxdepth 1 -type d -printf '%f\n'); 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 -r "s#/home[0-9]{0,2}/${_user}#/${home}/${_user}#g" /var/cpanel/userdata/${_user:-lolno}/*
              usermod -d /${home}/${_user} ${_user}
              if [[ ${_homedir} != /${home}/${_user} ]]; then
                if [[ ! -e ${_homedir} ]]; then
                  ln -vs /${home}/${_user} ${_homedir}
                  chown -vh ${_user}. ${_homedir}
                fi
              fi
            fi
          fi
        done
      fi
    done
    sed -i 's#/home/#/home9/#' /etc/passwd;
    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
}

prepare () {
#        system("$mig_base_dir/migration_tasks -h old -t pre_boot -m in_place");
  echo "$(date) :: $FUNCNAME: starting"
  if [ -z "${_mig_type}" ]; then
    echo "Failed: -m MIGRATION TYPE (remote/in_place) not set on ${_host} host"
    exit 1
  fi
  if [ "${_host}" == 'old' ]; then
    if [[ "${_mig_type}" == 'in_place' ]]; then
      /usr/local/bin/ea_current_to_profile --target-os=CentOS_8 --output=${_mig_in_place_new_root}/etc/cpanel/ea4/profiles/custom/ea4_eig_profile.json
      echo ''
      grep -q "${_mig_in_place_new_root}/proc" /proc/mounts || mount -t proc proc "${_mig_in_place_new_root}/proc"
      echo "$(date) :: $FUNCNAME: chroot start"
      cat <<- 'CHROOT_EOF' | chroot ${_mig_in_place_new_root} /bin/bash -l
        _mig_base_dir='/root/.server_migration'
        _centos_release=$(perl -ne 'm/ (\d)\.\d/ && print "$1"' /etc/redhat-release)
        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
        mkdir -vp /opt/eig_linux/etc/puppetfeatures/
        touch /opt/eig_linux/etc/puppetfeatures/{datacycle,remi_repo}
        sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config
        chmod -v 0 /usr/local/cpanel/bin/restartsrv_base
        mknod /dev/urandom c 1 9
        rm -vf /var/cpanel/sysinfo.config
        rm -vfr /var/cpanel/configs.cache/*
        find /var/cpanel/ -name \*.cache -type f -delete -print
        if [[ -d /var/cpanel/caches ]]; then
          rm -vfr /var/cpanel/caches/*
        fi
        puppet agent -t --server hensonm.hostgator.com --tags=yum_repos,puppet_agent,resolvers
        dnf clean all
        dnf update -y --exclude=kernel*
        wget -q -O /root/install_softac.sh --no-check-certificate http://files.softaculous.com/install.sh
        while [ $? -ne 0 ]; do
          sleep 5
          wget -q -O /root/install_softac.sh --no-check-certificate http://files.softaculous.com/install.sh
        done
        chmod 755 /root/install_softac.sh
        /root/install_softac.sh &>> ${_mig_base_dir}/softaculous_install.log
        rm -f /root/install_softac.sh
        touch /opt/eig_linux/etc/puppetfeatures/softaculous
        chmod 4555  /usr/local/cpanel/whostmgr/docroot/cgi/softaculous/bin/soft
        for i in {1..5}; do
           puppet agent -t
         done
        /usr/local/bin/ea_install_profile --install /etc/cpanel/ea4/profiles/custom/ea4_eig_profile.json || exit 1
        dnf install nf-php74-ea-compat --disableexcludes=main -y || exit 1
        /usr/local/cpanel/bin/rebuild_phpconf --no-restart --default=ea-php82 --nf-php74=lsapi || exit 1
        chmod -v 755 /usr/local/cpanel/bin/restartsrv_base
### move to post ###/root/bin/rebuild_http_suspension
CHROOT_EOF
      if [[ $? -eq 1 ]]; then
        echo "Failed: $FUNCNAME: chroot"
        exit 1
      fi
      echo "$(date) :: $FUNCNAME: chroot finished"
    else
      _ssh_keys_dst_uid=101
      _ssh_keys_src_uid=$(getent group ssh_keys | awk -F: {'print $3'})

      if [[ "${_ssh_keys_dst_uid}" != "${_ssh_keys_src_uid}" ]]; then
        groupmod -g "${_ssh_keys_dst_uid}" ssh_keys
        chgrp -v ssh_keys /usr/libexec/openssh/ssh-keysign
        find /etc/ssh -gid "${_ssh_keys_src_uid}" -exec chgrp -v ssh_keys {} \;
      fi
    fi
  fi
  echo "$(date) :: $FUNCNAME: finished"
}

pre_boot () {
  echo "$(date) :: pre_boot: starting"

  if [ -z "${_mig_type}" ]; then
    echo "Failed: -m MIGRATION TYPE (remote/in_place) not set on ${_host} host"
    exit 1
  fi

  if [ "${_host}" == 'new' ]; then
    systemctl start datacycle
    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
    ### TODO: Review for EL9
    if [ "${_centos_release}" -eq 7 ]; then
      fix_systemd
    fi
    if [[ ! -f /root/.server_migration/skip_homes ]]; then
      fix_homes
    fi
    chmod -v 755 /usr/sbin/mysqld
    umount /var/mysqltmp
    mount /var/mysqltmp
    if [ "${_centos_release}" -ge 7 ]; then
      chown -v mysql. /var/run/mysqld
      if [ "${_centos_release}" -gt 7 ]; then
        echo 'MYSQLD_OPTS="--upgrade=MINIMAL"' > /etc/sysconfig/mysql
      fi
      ### Needs to be removed so that MySQL upgrade works. Otherwise it crashes
      [[ -d '/var/lib/mysql/lost+found' ]] && rm -vfr '/var/lib/mysql/lost+found'
      service mysqld start || exit 1
      export HOSTNAME=$(awk '$1 == "HOST" {print $2}' /etc/wwwacct.conf)
      /usr/bin/hostnamectl set-hostname ${HOSTNAME}
      if ! getent group ssh_keys &> /dev/null; then
        yum reinstall -y openssh
        find /etc/ssh -gid 997 -exec chgrp -v ssh_keys {} \;
      fi
    else
      service mysql start || exit 1
      source /etc/sysconfig/network
      /bin/hostname ${HOSTNAME}
    fi
    if [ "${_centos_release}" -le 7 ]; then
      mysql_upgrade -s && touch /etc/eig_mysql_upgrade
    fi
    puppet agent --enable
    rm -vf /var/cpanel/sysinfo.config

    _cache_dirs=(
        "/var/cpanel/@pwcache"
        "/var/cpanel/caches"
        "/var/cpanel/configs.cache"
        "/var/cpanel/users.cache"
        "/var/cpanel/pw.cache"
        "/var/cpanel/user_pw_cache"
        "/var/cpanel/bandwidth.cache"
    )
    for _cache_dir in "${_cache_dirs[@]}"; do
        if [ -d "${_cache_dir}" ]; then
                rm -rfv "${_cache_dir}"/*
        fi
    done
    find /var/cpanel/ -type f \( -name cache -o -name \*.cache -o -name cache.json \) -delete -print

    service named start
    chmod 0 /usr/local/cpanel/scripts/find_outdated_services
    chattr +i /usr/local/cpanel/scripts/find_outdated_services
    dnf remove cpanel-analytics cpanel-koality-plugin cpanel-monitoring-plugin cpanel-plugin-monitoring-campaigns cpanel-sitejet-plugin cpanel-socialbee-plugin cpanel-xovi-plugin -y
    dnf install cpanel-analytics cpanel-koality-plugin cpanel-plugin-monitoring-campaigns cpanel-monitoring-plugin cpanel-sitejet-plugin cpanel-socialbee-plugin cpanel-xovi-plugin -y
    chmod -v 0755 /scripts/restartsrv*
    /usr/local/cpanel/cpkeyclt
    /scripts/upcp --sync
    # TODO fix php vers below 8.0
    if [ "${_centos_release}" -gt 7 ]; then
      /etc/dnf/universal-hooks/multi_pkgs/transaction/__WILDCARD__-php__WILDCARD__/009-phpconf.pl
      _php_vers=( $(/bin/awk -F: '/lsapi/ {print $1}' <(/usr/local/cpanel/bin/rebuild_phpconf --available)) )
      /usr/local/cpanel/bin/rebuild_phpconf $(printf -- ' --%s=lsapi' "${_php_vers[@]}")
      if [[ -x "${_mig_base_dir}/php_handler_update" ]]; then
        "${_mig_base_dir}/php_handler_update"
      fi
    fi
    chattr -Vi /usr/local/cpanel/scripts/find_outdated_services
    chmod 755 /usr/local/cpanel/scripts/find_outdated_services
    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
    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;
    chgrp -v mailtrap /usr/sbin/sendmail
    chmod -v 2755 /usr/sbin/sendmail
    sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config
    sed -i 's/^###\(.*\)/\1/' /var/spool/cron/root
    rm -vf /opt/eig_linux/etc/puppetfeatures/clamd_disable
    if ! mysql -BNe 'select User from user where User = "collectd"' -Dmysql | grep -q collectd; then
      _passwd=$(awk '/Password/ {print $2}' /etc/collectd.conf| sed 's/"//g')
      mysql -BNe "CREATE USER 'collectd'@'localhost' IDENTIFIED BY '${_passwd}'; GRANT USAGE ON *.* TO 'collectd'@'localhost';"
    fi
    if [[ ! -f '/opt/eig_linux/etc/puppetfeatures/disk_type' ]]; then
      if df -h /home1 | grep -q '1.5T'; then
        echo SSD > /opt/eig_linux/etc/puppetfeatures/disk_type
      fi
    fi
    if [[ ! -s /var/cpanel/cpnat ]]; then
      if [ "${_centos_release}" -gt 7 ]; then
        if [[ -s "${_mig_base_dir}/eth0.nmconnection.src" ]]; then
          mv -vf /etc/NetworkManager/system-connections/eth0.nmconnection "${_mig_base_dir}/eth0.nmconnection.backup"
          mv -vf "${_mig_base_dir}/eth0.nmconnection.src" /etc/NetworkManager/system-connections/eth0.nmconnection
          chmod -v 0600 /etc/NetworkManager/system-connections/eth0.nmconnection
        else
          echo "cannot find ${_mig_base_dir}/eth0.nmconnection.src" >&2
          exit 1
        fi
      else
        if [[ -s "${_mig_base_dir}/ifcfg-eth0.src" ]]; then
          mv -vf /etc/sysconfig/network-scripts/ifcfg-eth0 "${_mig_base_dir}/ifcfg-eth0.backup"
          mv -vf "${_mig_base_dir}/ifcfg-eth0.src" /etc/sysconfig/network-scripts/ifcfg-eth0
        else
          echo "cannot find ${_mig_base_dir}/ifcfg-eth0.src" >&2
          exit 1
        fi
      fi
    else
      if [[ -s "${_mig_base_dir}/nat_ip_map" ]]; then
        while read private_ip public_ip; do
        perl -i -pe "s/^\Q$public_ip\E\b/$private_ip/" /etc/reservedips /etc/reservedipreasons /opt/hgmods/shared_ips
        done <  "${_mig_base_dir}/nat_ip_map"
      fi
      if [[ -s "${_mig_base_dir}/account_ip_update" ]]; then
        "${_mig_base_dir}/account_ip_update"
        /scripts/updateuserdomains
        /scripts/updateuserdatacache
        /scripts/rebuildhttpdconf
      fi
    fi
    if [[ -s /etc/sysconfig/mysql ]]; then
      > /etc/sysconfig/mysql
    fi
    enable_services
    puppet agent --disable
  elif [ "${_host}" == 'old' ]; then
    if [[ "${_mig_type}" == 'remote' ]]; then
      if [[ -s /etc/ips ]]; then
        mv -v /etc/ips{,.migrated}
      fi
      if [ "${_centos_release}" -gt 7 ]; then
        if [[ -s /etc/NetworkManager/system-connections/eth0.nmconnection ]]; then
          mv -fv /etc/NetworkManager/system-connections/eth0.nmconnection "${_mig_base_dir}/eth0.nmconnection.backup"
        fi
      else
        if [[ -s /etc/sysconfig/network-scripts/ifcfg-eth0 ]]; then
          mv -vf /etc/sysconfig/network-scripts/ifcfg-eth0 "${_mig_base_dir}/ifcfg-eth0.backup"
        fi
      fi
      _is_virtual=$(/usr/bin/facter is_virtual)
      if [ "${_is_virtual}" == 'true' ]; then
        shutdown -h now
      fi
    elif [[ "${_mig_type}" == 'in_place' ]]; then
      sed -i "s#ETHDEV.*#ETHDEV $(ip route show default 0.0.0.0/0 | grep -Po '(?<=dev )\S+')#" ${_mig_in_place_new_root}/etc/wwwacct.conf
      _homes=$(grep -cP '/home\d' /etc/fstab)
      sed -i "s#HOMEMATCH .*#HOMEMATCH home[1-${_homes}]#" ${_mig_in_place_new_root}/etc/wwwacct.conf
      cp -av /etc/cpanel/ea4/php.conf ${_mig_in_place_new_root}/${_mig_base_dir}/etc_cpanel_ea4_php.conf
      grep -q "${_mig_in_place_new_root}/proc" /proc/mounts || mount -t proc proc "${_mig_in_place_new_root}/proc"
      echo "$(date) :: pre_boot: chroot start"
      cat <<- 'CHROOT_EOF' | chroot ${_mig_in_place_new_root} /bin/bash -l
        _mig_base_dir='/root/.server_migration'
        _centos_release=$(perl -ne 'm/ (\d)\.\d/ && print "$1"' /etc/redhat-release)
        if [ "${_centos_release}" -ge 9 ]; then
          mv -fv /root/.server_migration/eth0.nmconnection /etc/NetworkManager/system-connections
        else
          mv -fv /root/.server_migration/ifcfg-eth0 /etc/sysconfig/network-scripts
        fi
        find /etc/ssh/ \( -name ssh\*.pub -o -name ssh\*_key \) -delete -print
        groupdel ssh_keys
        rm -vf /etc/ssh/ssh_host_*
        yum reinstall -y openssh
        rm -vf /var/cpanel/sysinfo.config
        rm -vfr /var/cpanel/configs.cache/*
        find /var/cpanel/ -name \*.cache -type f -delete -print
        if [[ -d /var/cpanel/caches ]]; then
          rm -vfr /var/cpanel/caches/*
        fi
### move to post ###/root/bin/rebuild_http_suspension
CHROOT_EOF
    echo "$(date) :: pre_boot: chroot finished"
    fi
  fi
  echo "$(date) :: pre_boot: finished"
}

post_boot () {
  echo "$(date) :: post_boot: starting"
  if [ "${_host}" == 'new' ]; then
    while ! ping -q -c 1 8.8.8.8; do
      echo "waiting for network"
      sleep 2
    done
    payload=$(cat <<-EOF
        {
          "hostname": "${HOSTNAME}",
          "task": "post_boot",
          "status": "started"
        }
	EOF
    )

    curl -v -X POST -H "Content-Type: application/json" \
      -d "$payload" \
      "https://migration-api.sandbox.nf.hostgator.com/api/update"

    if [[ -s /etc/ips ]]; 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
    fi
    rm -vf "/root/.mig-${HOSTNAME}"
    rm -vf /etc/cron.d/post_mig_update
    if [[ ! -s /var/cpanel/cpnat ]]; then
      echo $(dig +short "${HOSTNAME}") > /var/cpanel/mainip
    fi
    sed -i "/${HOSTNAME//.*}/d" /etc/hosts
    /usr/local/cpanel/scripts/fixetchosts
    /root/bin/rebuild_http_suspension
    perl /opt/hgmods/multi_shared.pl
    /scripts/rebuildhttpdconf
    if [[ -s /etc/ips ]]; 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
    fi
    ### TODO commenting this out for now
    # /scripts/removeacct nf00wpbenchs --force
    # yum install -y store-wp-bench --enablerepo=hgrepo-testing
    ###
    yum install -y 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
    /etc/cron.daily/store_php_version_check
    puppet agent --enable
    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
    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
    /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

    payload=$(cat <<-EOF
        {
          "hostname": "${HOSTNAME}",
          "task": "post_boot",
          "status": "completed"
        }
	EOF
    )

    curl -v -X POST -H "Content-Type: application/json" \
      -d "$payload" \
      "https://migration-api.sandbox.nf.hostgator.com/api/update"

    if [[ -f /opt/eig_linux/etc/puppetfeatures/datacycle ]]; then
      if [[ -f /opt/eig_linux/data/backupdates.yaml ]]; then
        /root/bin/backuphelper setup
      fi
    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}" -ge 7 ]; then
    _services=(cpanel crond collectd atd dovecot httpd pure-ftpd exim sshd_client mysqld clamd@scan.service monit osqueryd grafana-agent taniumclient observiq-otel-collector cpanel_exporter exim_exporter bind_exporter spamd proc-monitor apache-monitor tailwatchd cpanellogd cpdavd named)
    for service in ${_services[@]}; do
      echo "$(date) :: disable_services: stopping: ${service}"
      systemctl --now disable "${service}"
    done
  else
    _services=(cpanel crond collectd atd zabbix-agent dovecot httpd pure-ftpd exim sshd_client mysql clamd.scan monit)
    for service in ${_services[@]}; do
      echo "$(date) :: disable_services: stopping: ${service}"
      service "${service}" stop
    done
  fi
  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
      echo "setting up maintenance page"
      yum install -y --disablerepo='*' --enablerepo=hgrepo thttpd
      cd /opt/thttpd/htdocs/
      ln -svf upgrade.html index.html
      service thttpd start
      if [ "${_centos_release}" -ge 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 datacycle eigeximlogd gatordovelogintrackd gatorftpwatch gatorlogintrackd nxlog spamd apache-monitor proc-monitor; do
        if [ "${_centos_release}" -ge 7 ]; then
          systemctl --now disable "${service}"
        else
          service "${service}" stop
          chkconfig "${service}" off
        fi
    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
    yum update -y
  fi
}

enable_services () {
  puppet agent --enable
  if [ "${_centos_release}" -ge 7 ]; then
    _services=(cpanel crond collectd atd dovecot httpd pure-ftpd exim sshd_client mysqld clamd@scan.service monit osqueryd grafana-agent taniumclient observiq-otel-collector cpanel_exporter exim_exporter bind_exporter spamd apache-monitor proc-monitor tailwatchd cpanellogd cpdavd datacycle named)
  else
    _services=(cpanel crond collectd atd zabbix-agent dovecot httpd pure-ftpd exim sshd_client mysql clamd.scan monit)
    for service in ${_services[@]}; do
      echo "$(date) :: enable_services: starting: ${service}"
      service ${service} start
    done
  fi

  if [ "${_host}" == 'old' ]; then
    echo "removing up maintenance page"
    service thttpd stop
    yum remove -y --disablerepo='*' --enablerepo=hgrepo thttpd
    > /root/.motd
    rm -vfr /opt/thttpd/htdocs/
    chattr -ia /etc/stats.conf
    chmod -v 755 /scripts/restartsrv*
    if [ "${_centos_release}" -ge 7 ]; then
      for service in ${_services[@]}; do
        echo "enable c7+ service: ${service}"
        systemctl enable --now ${service};
      done
    else
      for service in ${_services[@]}; do
        echo "enable c6 service: ${service}"
        chattr -V -i /etc/init.d/${service}
        chmod -v 0755 /etc/init.d/${service}
        service ${service} start
      done
    fi
    if [[ -s /etc/ips.migrated ]]; then
      mv -v /etc/ips{.migrated,}
    fi
    shutdown -rf now
  elif [ "${_host}" == 'new' ]; then
    if [ "${_centos_release}" -ge 7 ]; then
      for service in ${_services[@]}; do
        echo "enable c7+ service: ${service}"
        systemctl enable ${service};
      done
    else
      for service in ${_services[@]}; do
        echo "enable c6 service: ${service}"
        chattr -V -i /etc/init.d/${service}
        chmod -v 0755 /etc/init.d/${service}
      done
    fi
  fi
}

gen_ifcfg_eth0 () {
  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'})
  if [ "${_host}" == 'old' ]; then
    _ifcg=/root/.server_migration/ifcfg-eth0.src
  else
    _ifcg=/root/.server_migration/ifcfg-eth0.dst
  fi
  cat > "${_ifcg}" <<-ICFG_EOF
	DEVICE=eth0
	BOOTPROTO=static
	ONBOOT=yes
	TYPE=Ethernet
	IPV6INIT=no
	IPADDR=${_ip}
	PREFIX=${_prefix}
	GATEWAY=${_gateway}
	MTU=1400
	ICFG_EOF
}

gen_nm_eth0 () {
  echo "$(date) :: gen_nm_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'})

  if [ "${_host}" == 'old' ]; then
    _nm=/root/.server_migration/eth0.nmconnection.src
  else
    _nm=/root/.server_migration/eth0.nmconnection.dst
  fi
  cat > "${_nm}" <<-NM_EOF
	[connection]
	id=eth0
	type=ethernet
	interface-name=eth0
	
	[ethernet]
	mtu=1400
	
	[ipv4]
	address1=${_ip}/${_prefix},${_gateway}
	method=manual
	
	[ipv6]
	method=disabled
	NM_EOF
}

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;
