#!/bin/bash

LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8
LANGUAGE=en_US.UTF-8
DEST=/root/cl-report
UPLOAD_URL=https://doctor.cloudlinux.com/doctor/upload
CAT=`command -v cat`
UNAME=`command -v uname`
CP="Unknown"
SERVER_ID=
OS_NAME=""
OS_VERSION=""
TIMEOUT_CMD=`command -v timeout`
TIMEOUT_DEFAULT=60
TIMEOUT_EXIT_CODE=124


cleanup() {
  rm -f $DEST $DEST.wget
}

test_curl() {
    command -v curl 2>&1 >/dev/null
    return $?
}

test_wget() {
  command -v wget 2>&1 >/dev/null
  if [ 0 -eq $? ]; then
    if [ -x `command -v wget` ]; then
    return 0
    fi
  fi
  return 1
}

curl_upload() {
 curl -s -H "serverid: $SERVER_ID" -F reportfile=@"$DEST" $UPLOAD_URL
}

wget_upload() {

    echo -e "--FILEUPLOAD\r\n" > $DEST.wget
    echo -e "--FILEUPLOAD\r\n" > $DEST.wget
    echo -e "Content-Disposition: form-data; name=\"reportfile\"; filename=\"$DEST\"\r\n" >> $DEST.wget
    echo -e "Content-Type: application/octet-stream\r\n" >> $DEST.wget
    echo -e "Media Type: application/octet-stream\r\n\r\n" >> $DEST.wget
    cat $DEST >> $DEST.wget
    echo -e "--FILEUPLOAD--\r\n" >> $DEST.wget
    wget -O - -qq -t 1 --header="serverid: $SERVER_ID" --header="Content-type: multipart/form-data; boundary=FILEUPLOAD" --post-file $DEST.wget $UPLOAD_URL
}

upload() {
 if test_curl
 then
     curl_upload
 else
     wget_upload
 fi
 echo
}

mecho(){
 silent_run "echo $1"
}

start(){
 if ! test_wget; then
     if ! test_curl; then
     echo "Cannot find wget or curl"
     fi
     #echo "Using curl"
 fi
 echo "------ CL INFO ---" > $DEST
}

catch_error() {
  if [[ ! -z $2 ]]; then
    echo "CMD_ERROR ($1): $2" >> $DEST 2>&1
  fi
}

sep() {
 silent_run "echo ------ $1 ---"
}


run_with_timeout() {
  local cmd="$1"
  local status

  $TIMEOUT_CMD "$TIMEOUT_DEFAULT" sh -c "$cmd"
  status=$?

  if [[ "$status" -eq "$TIMEOUT_EXIT_CODE" ]]; then
    echo "Command timed out after $TIMEOUT_DEFAULT seconds: $cmd" >&2
  fi

  return $status
}

check_timeout_and_run() {
  local cmd="$1"
  local status

  if [[ -z "$TIMEOUT_CMD" ]]; then
    sh -c "$cmd"
    status=$?
  else
    run_with_timeout "$cmd"
    status=$?
  fi

  return $status
}


run() {
 sep "$1"
 error=$({ check_timeout_and_run "$1" >> $DEST; } 2>&1)
 catch_error "$1" "$error"
}

silent_run() {
 error=$({ exec $1 >> $DEST; } 2>&1)
 catch_error "$1" "$error"
}

dump() {
 sep "cat $1"
 silent_run "$CAT $1"
}

get_server_id() {
  if [ -f /etc/sysconfig/rhn/systemid ]; then
    SERVER_ID=`grep '<value><string>ID-' /etc/sysconfig/rhn/systemid |sed -n 's:.*<string>ID-\(.*\)</string>.*:\1:p'`
  else
    SERVER_ID='NA'
  fi
}

dump_server_id() {
  get_server_id
  sep "SERVER ID"
  mecho "serverid: $SERVER_ID"
}

dump_dashboard_token_and_link() {
  local dashboard_token
  if [ -z "$SERVER_ID" ]; then
      get_server_id
  fi
  sep "Dashboard info"
  dashboard_token=$(cat /var/lve/dashboard_certificate 2>/dev/null)
  mecho "Token: ${dashboard_token:-Dashboard certificate not found}"
  if [ -n "$dashboard_token" ] && [ "$SERVER_ID" != "NA" ]; then
    printf "https://stat-api.imunify360.com/api/clos-stat?system_id=ID-%s&security_token=%s\n" "$SERVER_ID" "$dashboard_token" >> $DEST
  else
    return
  fi
}

detect_cp() {
    CP_VERSION="Unknown"
    SOFTACULOUS=0
    if [ -d "/usr/local/psa/admin/" ]; then
        CP="Plesk"
        CP_VERSION=`cat /usr/local/psa/version`
        if [ -e "/usr/local/softaculous" ]; then SOFTACULOUS=1; fi
    fi
    if [ -d "/usr/local/cpanel/whostmgr/docroot/" ]; then
        CP="cPanel"
        CP_VERSION=`/usr/local/cpanel/cpanel -V`
        if [ -e "/usr/local/cpanel/whostmgr/cgi/softaculous" ]; then SOFTACULOUS=1; fi
    fi
    if [ -d "/usr/local/interworx/" ]; then
        CP="InterWorx"
        CP_VERSION=`cat /usr/local/interworx/iworx.ini|grep version`
        if [ -e "/usr/local/softaculous" ]; then SOFTACULOUS=1; fi
    fi
    if [ -x "/usr/local/ispmgr/bin/ispmgr" ] || [ -x "/usr/local/mgr5/sbin/mgrctl" ]; then
        CP="ISPmanager"
        if [ -x "/usr/local/ispmgr/bin/ispmgr" ]; then
            CP_VERSION=$(/usr/local/ispmgr/bin/ispmgr -v)
        else
            CP_ISP_TYPE=""
            if CP_VERSION=$(/bin/rpm -q --queryformat "[%{VERSION}]" ispmanager-business-common) &&
                    [ -n "$CP_VERSION" ]; then
                CP_ISP_TYPE="Master"
            elif CP_VERSION=$(/bin/rpm -q --queryformat "[%{VERSION}]" ispmanager-node-common) &&
                    [ -n "$CP_VERSION" ]; then
                CP_ISP_TYPE="Node"
            elif CP_VERSION=$(/bin/rpm -q --queryformat "[%{VERSION}]" ispmanager-lite-common) &&
                    [ -n "$CP_VERSION" ]; then
                CP_ISP_TYPE="Lite"
            else
                CP_VERSION="Unknown"
            fi
        fi
        if [ -e "/usr/local/softaculous" ]; then SOFTACULOUS=1; fi
    fi
    if [ -d "/usr/local/directadmin/plugins/" ]; then
        CP="DirectAdmin"
        CP_VERSION=`/usr/local/directadmin/custombuild/build versions|sed -n 2p|cut -d":" -f2`
        if [ -e "/usr/local/directadmin/plugins/softaculous" ]; then SOFTACULOUS=1; fi
    fi
    if [ -d "/usr/local/hostingcontroller/" ]; then
        CP="Hosting Controller"
        if [ -e "/usr/local/softaculous" ]; then SOFTACULOUS=1; fi
    fi
    if [ -d "/hsphere/shared" ]; then
        CP="H-Sphere"
    fi
    sep "Control Panel"
    mecho "CP: $CP"
    mecho "VERSION: $CP_VERSION"
    mecho "SOFTACULOUS: $SOFTACULOUS"
    if [ -n "${CP_ISP_TYPE}" ]; then
        mecho "ISP TYPE: ${CP_ISP_TYPE}"
    fi
}

run_hsphere_apache_command() {
    local pid exe

    [ "$1" = "--" ] || return 1
    shift
    pid=$(pgrep -f "httpd.*hsphere" | grep -v cpanel | head -1)
    [ -n "$pid" ] || return 0

    [ -r "/proc/$pid/exe" ] || return 0
    exe=$(readlink -f "/proc/$pid/exe") || return 0
    if [ -n "$exe" ] || [ -x "$exe" ]; then
        return 0
    fi

    # Reject unsafe execution locations
    case "$exe" in
        /tmp/*|/var/tmp/*|/dev/shm/*|/home/*|/root/*)
            logger -t report "Refusing to run httpd from unsafe path: $exe (pid=$pid)"
            return 0
            ;;
    esac

    # Reject writable binaries
    if find "$exe" -perm /022 -print | grep -q .; then
        logger -t report "Refusing to run writable httpd binary: $exe"
        return 0
    fi

    logger -t report "Executing httpd from $exe with args: $*"

    "$exe" "$@"
}

apache_info() {
    sep "Apache Info"
    if [ $CP == "cPanel" ]; then
          /usr/sbin/httpd -V >> $DEST 2>&1
    elif [ $CP == 'H-Sphere' ]; then
        run_hsphere_apache_command -- -V >> $DEST 2>&1
    else
        apachectl -V >> $DEST 2>&1
    fi
}

apache_modules() {
    sep "Apache Modules"
    if [ $CP == "cPanel" ]; then
          /usr/sbin/httpd -M >> $DEST 2>&1
    elif [ $CP == 'H-Sphere' ]; then
        run_hsphere_apache_command -- -M >> $DEST 2>&1
    else
        apachectl -M >> $DEST 2>&1
    fi
}

apache_status() {
    sep "Apache Status"
    if [ $CP == "cPanel" ]; then
          /usr/sbin/httpd status >> $DEST 2>&1
    elif [ $CP == 'H-Sphere' ]; then
        run_hsphere_apache_command -- status >> $DEST 2>&1
    else
        apachectl status >> $DEST 2>&1
    fi
}

apache_fullstatus() {
    sep "Apache Full Status"
    if [ $CP == "cPanel" ]; then
          /usr/sbin/httpd fullstatus >> $DEST 2>&1
    elif [ $CP == 'H-Sphere' ]; then
        run_hsphere_apache_command -- fullstatus >> $DEST 2>&1
    else
        apachectl fullstatus >> $DEST 2>&1
    fi
}

cPanel_forkbomb() {
    if [ $CP == 'cPanel' ]; then
        sep "cPanel Fork Bomb Protectoin"
        grep "#cPanel Added Limit Protections" /etc/bashrc >> $DEST 2>/dev/null
        grep "#cPanel Added Limit Protections" /etc/profile >> $DEST 2>/dev/null
        if [ -e /etc/profile.d/limits.sh ]; then
            echo /etc/profile.d/limits.sh exists >> $DEST
        fi

        if [ -e /etc/profile.d/limits.csh ]; then
            echo /etc/profile.d/limits.csh exists >> $DEST
        fi


    fi

}

get_main_ip() {
  if [ "$1" == "4" ]; then
      sep "Main IP"
  else
      sep "Main IPv6"
  fi
 
 RAND="$(echo $(hostname -s) | sha1sum | cut -c1-20)-$RANDOM"
 if test_curl
 then
    curl -$1 -s -L http://cloudlinux.com/showip.php?$RAND >>$DEST 2>&1
 else
    wget -qq --inet$1-only -O - http://cloudlinux.com/showip.php?$RAND >>$DEST 2>&1
 fi
 echo >>$DEST 2>&1
}

litespeed_arch() {
    sep "LiteSpeed Arch"
    file `readlink -f  /usr/local/lsws/bin/lshttpd` >> $DEST 2>&1
}

multiphp_settings() {
    if [ "$CP" == "cPanel" ]; then
       sep "MultiPHP Settings"
       whmapi1 php_get_vhost_versions | \
           awk '{
               match($0,"[[:blank:]]*(account: )[[:alnum:]]*"); "id -u "substr($2,0,RLENGTH)|getline id; printf substr(id","$2,0,RLENGTH);
               match($0,"php_fpm: 0"); printf substr(",no,",0,RLENGTH);
               match($0,"php_fpm: 1"); printf substr(",yes,",0,RLENGTH);
               match($0,"system_default: 1"); printf substr("inherited",0,RLENGTH);
               match($0,"[[:blank:]]*(vhost: )[[:alnum:]].*"); printf substr(","$2"\n",0,RLENGTH)
           }' | \
           sort -n -k1 | \
           awk 'BEGIN {
               printf "%-6s %-18s %s","ID","| Account", "| FPM | PHP Version | Domain\n";
               FS=","
           }
           {
               printf "%-6s %-18s %-5s %-13s %s", $1,"| "$2,"| "$3,"| "$4,"| "$5"\n"
           }' >> $DEST 2>&1
    fi
    if [ "$CP" == "Plesk" ]; then
      sep "Plesk PHP Selector"
      mecho "All PHP versions and handlers:"
      plesk db "select s.login, d.name, h.php_handler_id from domains d join hosting h on d.id=h.dom_id join sys_users s on h.sys_user_id=s.id;" >> $DEST 2>&1
      mecho "List of PHP handlers associations:"
      silent_run "plesk bin php_handler --list"
    fi
}

get_os() {
  if [ -e /etc/os-release ]; then
    OS_NAME=$(cat /etc/os-release | awk -F '=' '/^ID_LIKE/{print $2}' | awk '{print $1}' | tr -d '"')
    if [ -z "$OS_NAME" ]; then
      OS_NAME=$(awk -F '=' '/^ID=/{print $2}' /etc/os-release | tr -d '"')
    fi
  else
    OS_NAME=$(cat /etc/redhat-release | awk '{print $1}')
  fi
}

get_os_version() {
  if [ -e /etc/os-release ]; then
    OS_VERSION=$(awk -F'=' '/VERSION_ID/{ gsub(/"/,""); print $2}' /etc/os-release | cut -d'.' -f 1)
  else
    OS_VERSION=$(cat /etc/redhat-release | grep -oP '\d' | head -1)
  fi
}

start
echo "Generating report..."
get_os
get_os_version
dump_server_id
dump_dashboard_token_and_link
run "date"
run "$CAT /proc/cpuinfo"
run "$UNAME -a"
run "$UNAME -r"
run "$UNAME -m"
run "$UNAME -p"
run "$UNAME -o"
run "$CAT /etc/sysconfig/rhn/up2date"

if [ -e /etc/os-release ]; then
  dump "/etc/os-release"
fi

if [ "$OS_NAME" == "debian" ]; then
  run "dpkg -l"
  run "dpkg-query -W -f='\${Package}|\${Version}|\${Architecture}\n'"
  run "dpkg-query -W -f='\${Package}|\${Version}|\${Architecture}\n' ea-apache*"
elif [ "$OS_NAME" == "alpine" ]; then
  run "apk info -v"
else
  dump "/etc/redhat-release"
  run "rpm -q -a"
  run 'rpm -q -a --queryformat="%{N}|%{V}-%{R}|%{arch}\n"'
  run 'rpm -q -a --queryformat="%{N}|%{V}-%{R}|%{arch}\n" "ea-apache*"'
fi

run "stat / | grep 'Birth'"
run "last reboot"
dump "/etc/sysconfig/kernel"
dump "/proc/uptime"
dump "/proc/loadavg"
dump "/proc/vmstat"
dump "/proc/devices"
dump "/proc/diskstats"
dump "/proc/cmdline"
dump "/proc/mdstat"
dump "/proc/meminfo"
dump "/proc/swaps"
dump "/proc/filesystems"
dump "/proc/mounts"
dump "/proc/self/mountinfo"
dump "/proc/interrupts"
dump "/boot/grub/grub.conf"
dump "/etc/default/grub"
run "grep vmlinuz /boot/grub2/grub.cfg| sed 's/root=.*//'"
dump "/boot/grub2/grub.cfg"
dump "/boot/grub2/grubenv"
run "ls -al /boot/grub2/grubenv"
dump "/proc/zoneinfo"
run "ls -la /etc/grub.conf /boot/grub/grub.conf /boot/grub/menu.lst"
run "ls -l /boot"
run "ls -l /var/lve/"
run "printenv"
dump "/etc/sysconfig/i18n"
litespeed_arch
run "lvectl list"
run "lvectl list-user"
run 'lveinfo -d --period=1d --by-fault=any --limit=30 --show-columns="ID,lCPU,CPUf,lPMem,PMemF,lEP,EPf,lNPROC,NPROCf,lIO,IOf,lIOPS,IOPSf"'
run "php -i"
run "lspci"
run "ps auxwf"
run "ps auxwH"
run "ps hax -o rss,user | awk '{a[\$2]+=\$1;}END{for(i in a)print i\" \"int(a[i]/1024+0.5);}' | sort -rnk2"
dump "/sys/block/[xsh]*d*/queue/scheduler"
run "ls -a /sys/block"
run "mount"
dump "/etc/fstab"
run "iostat -x -h -p ALL"
run "vmstat 1 3"
run "ifconfig|grep 'inet addr'|wc -l"
run "netstat -ntu | awk -F\"[ :]+\" 'NR>2{print \$6}'|sort|uniq -c|sort -nr"
run "dbctl list"
run "dbtop -c"
run "top -b -n1"
run "iotop -b -n1"
run "df -h"
run "df -i"
dump "/etc/modprobe.d/blacklist*"
run "lsblk -f"
run "blkid"

if [ "$OS_NAME" == "debian" ]; then
  run "ls -a /etc/apt/sources.list.d"
  dump "/etc/apt/sources.list"
  for file in $(ls /etc/apt/sources.list.d/*.list /etc/apt/sources.list.d/*.sources 2>/dev/null); do
    dump "$file"
  done
elif [ "$OS_NAME" == "alpine" ]; then
  dump "/etc/apk/repositories"
  for file in $(ls /etc/apk/repositories.d/* 2>/dev/null); do
    dump "$file"
  done
else
  run "ls -a /etc/yum.repos.d"
  for file in $(ls /etc/yum.repos.d/*.repo 2>/dev/null); do
    dump "$file"
  done
fi

run "grep Port /etc/ssh/sshd_config"

if [ "$OS_NAME" == "debian" ]; then
  for file in `ls /etc/apt/apt.conf.d 2>/dev/null`; do
    dump "/etc/apt/apt.conf.d/$file"
  done
  run "apt-cache policy"
elif [ "$OS_NAME" == "alpine" ]; then
  run "apk policy"
else
  if [ "$OS_VERSION" -ge 8 ]; then
    dump "/etc/dnf/dnf.conf"
    dump "/etc/dnf/modules.d/*"
  else
    dump "/etc/yum.conf"
  fi
  run "tail -n 20 /etc/yum/pluginconf.d/*"
  run "yum repolist"
fi

dump "/etc/resolv.conf"
dump "/proc/lve/list"
dump "/proc/user_beancounters"
run "dmidecode"
run "virt-what"
run "ipcs -m|sed -e s/-/=/g"
run "strings /opt/suphp/sbin/suphp|grep lve"
run "strings /usr/local/apache/bin/suexec|grep lve"
run "strings /usr/sbin/suexec|grep lve"
run "/usr/local/cpanel/bin/rebuild_phpconf --current"
run "cagefsctl --display-user-mode"
run "cagefsctl --cagefs-status"
run "cagefsctl --sanity-check"
run "cagefsctl --list-enabled"
run "cagefsctl --list-disabled"
run "cat /etc/cagefs/cagefs.mp"
run "grep pam_lve /etc/pam.d/*"
run "mysql -V"
run "lsmod"
run "locale"
run "grep -i rlimit /etc/httpd/conf/*.conf /etc/httpd/conf/*/*.conf /etc/httpd/conf.d/*.conf"
run "sysctl -a"
dump "/etc/sysctl.conf"
run "sestatus"
run "lveps -p"
dump "/etc/container/ve.cfg"
dump "/etc/sysconfig/lvestats"
dump "/etc/sysconfig/lvestats2"
dump "/etc/sysconfig/lvestats2.readonly"
run "ls -l /etc/cpanel/ea4"
dump /etc/cpanel/ea4/php.conf
dump /etc/cpanel/ea4/paths.conf
dump /etc/mdadm.conf
run "sar -W -f /var/log/sa/sa$(date +%d)"
run "sar -W -f /var/log/sa/sa$(date +%d -d yesterday)"
run "sar -q -f /var/log/sa/sa$(date +%d)"
run "sar -q -f /var/log/sa/sa$(date +%d -d yesterday)"
run "sar -u -f /var/log/sa/sa$(date +%d)"
run "sar -u -f /var/log/sa/sa$(date +%d -d yesterday)"
run "ls -l /usr/share/cagefs/.cpanel.multiphp/opt/cpanel/ea-php*/root/usr/bin/*php*"
run "ls -l /usr/share/cagefs/.cpanel.multiphp/opt/cpanel/ea-php*/root/etc/php.ini*"
run "ls -l /opt/cpanel/ea-php*/root/usr/bin/*php*"
run "ls -l /opt/cpanel/ea-php*/root/etc/php.ini*"
run "find /etc/cl.php.d -ls"
run "ls -la /var/cpanel/cpanel.config"

for file in `ls /etc/sysconfig/lvestats.config/*.cfg 2>/dev/null`; do
  dump $file
done
dump "/etc/sysconfig/cloudlinux"
run "tail -n 100 /var/log/lve-stats.log"
run 'tail -n 100 /var/log/cagefs.log'
run "tail -n 500 /var/log/up2date"
run "tail -n 500 /var/log/cldeploy.log"
run "tail -n 500 /usr/share/lve/dbgovernor/governor_install.log"
run '/opt/alt/python27/bin/python -c "from lvestats.lib.ustate import get_lveps; print get_lveps()"'
run "ls -la /etc/cl.selector"
dump "/etc/cl.selector/defaults.cfg"
dump "/etc/cl.selector/selector.conf"
dump "/etc/container/mysql-governor.xml"
if [ "$OS_NAME" != "debian" ]; then
  if [ "$OS_VERSION" -ge 8 ]; then
    run 'grep "Installed\|Removed\|Upgraded" /var/log/dnf.log* | tail -n 500'
  else
    run 'tail -n 500 /var/log/yum.log'
  fi
fi
run 'tail -n 100 /var/log/alt-php-xray/manager.log'
run 'tail -n 100 /var/log/alt-php-xray/agent.log'
run 'tail -n 100 /var/log/httpd/error_log'
run 'tail -n 100 /var/log/apache2/error_log'
run 'tail -n 100 /var/log/nginx/error.log'
run 'tail -n 100 /var/log/dbgovernor-error.log'
run 'tail -n 100 /var/log/messages'
run 'ls /var/crash'
run 'getent group linksafe'
run 'repquota -a'
dump '/etc/container/cl-quotas.dat'
run 'cldiag --all'
run 'cldiag --check-cm-all'
run 'cldetect --detect-cp-full'
run 'cldetect --detect-edition'

if [ "$OS_NAME" != "debian" ]; then
  run 'service httpd status'
else
  run 'service apache2 status'
fi
run 'service lsws status'
run 'service nginx status'
run 'service mysqld status'
run 'service mysql status'
run 'service mariadb status'
run 'service cl_plus_sender status'

# CL Elevate-related logs. Only present on the system if an upgrade attempt has been made.
if [ -d "/var/log/leapp/" ]; then
  if [ -n "$(ls -A /var/log/leapp/)" ]; then
    for file in /var/log/leapp/*
    do
      dump "$file"
    done
  fi
  if [ $CP == 'cPanel' ] && [ -f "/var/log/elevate-cpanel.log" ]; then
    dump "/var/log/elevate-cpanel.log"
  fi
fi

get_main_ip 4
get_main_ip 6
detect_cp
multiphp_settings
apache_info
apache_modules
apache_status
apache_fullstatus
cPanel_forkbomb
echo "Uploading..."
echo -n "Key: "
upload
cleanup
echo "Please, provide above mentioned key to CloudLinux Support Team"
