Kerala Cyber Warriors
KCW Uploader V1.1

Path : /proc/thread-self/root/scripts/
File Upload :
Current File : //proc/thread-self/root/scripts/agent360.sh

#!/bin/bash

#: Variables :#
set -o nounset
export LC_ALL=C

install_log="/var/log/agent360-install.log"
log_file="/var/log/agent360.log"
default_bin="/usr/local/bin/agent360"
agent_config_file="/etc/agent360.ini"
agent_token_file="/etc/agent360-token.ini"
config_tpl="https://monitoring.platform360.io/agent360.ini"
agent_sysd_service="/etc/systemd/system/agent360.service"
agent_sysv_service="/etc/init.d/agent360"
agent_bsd_service="/etc/rc.d/agent360"

rhel_os_list=( "centos" "almalinux" "cloudlinux" "amazon" "fedora" "sangoma" "oracle" "scientific" "freepbx" "rhel" "virtuozzo" "rocky" )
deb_os_list=( "ubuntu" "debian" )
free_os_list=( "freebsd" )

default_pkgs=( "gcc" )
deb_py_pkgs=( "python3-dev" "python3-setuptools" "python3-pip" )
rhel_py_pkgs=( "which" "python3" "python3-devel" "libevent-devel" )

#: Check root privilege :#
if [ "$(id -u)" != "0" ];
then
   echo -e "\\e[31m  [ERROR] Installer needs root permission to run, please run as root.\\e[m"
   exit 1
fi

#######################
## PROCESS ARGUMENTS ##
#######################

automon=0
skip_deps=0
token=
tags=
declare -a positional_args=()
while [[ $# -gt 0 ]]; do
  case $1 in
    --skip-deps|--skip-dep-install)
      skip_deps=1
      shift
      ;;
    --token)
      token="$2"
      shift
      shift
      ;;
    --tags)
      tags="$2"
      shift
      shift
      ;;
    # As I read it the older code just accept add-websites as an argument
    add-websites|--add-websites)
      automon=1
      shift
      ;;
    *)
      positional_args+=("$1")
      shift;
      ;;
  esac
done

# Accept poitional syntax too
token=${token:=${positional_args[0]}}
tags=${tags:=${positional_args[1]:-}}

#######################
## Library functions ##
#######################

#: Functions :#
logging(){
	dt=`date "+%Y-%m-%d %H:%M:%S"`
	echo -e '['$dt'] Executing: '$@ >> "$install_log" 2>&1
    "$@" >> "$install_log" 2>&1
}

error_handling(){
	rc=$?
	if [ "$rc" != "0" ]; then
		if [ $# -eq 0 ]; then
			echo -e "\\e[31m  [ERROR] An error occured. Please check the log ${install_log} for details\\e[m"
		else
			echo -e "\\e[31m  [CRITICAL] A critial error occured!\\e[m"
			echo -e "\\e[31m  The installation aborted, please check the log ${install_log}\\e[m"
			exit
		fi
	fi
}

get_os_release(){
	RELEASE=$(cat /etc/os-release | grep ^NAME | head -1 | awk -F'"' '{print $2}' | awk '{print $1}')
	if [[ -n $RELEASE ]]; then
		OS_RELEASE=$RELEASE
		OS_NAME=$(echo "$OS_RELEASE" | tr '[:upper:]' '[:lower:]')
	else
		OS_RELEASE=""
		echo -e "\\e[31m  [ERROR] Unable to find the Linux distribution name\\e[m"
		exit
	fi

	if [ $OS_RELEASE == "Red" ]; then
		OS_RELEASE="RHEL"
		OS_NAME=$(echo "$OS_RELEASE" | tr '[:upper:]' '[:lower:]')
	fi
}

get_os_version(){
	VERSION=$(cat /etc/os-release | grep ^VERSION | head -1 | awk -F'"' '{print $2}' | awk -F'[^0-9]+' '{ print $1 }')
	if [[ -n $VERSION ]]; then
		OS_VERSION=$VERSION
	else
		OS_VERSION=""
		echo -e "\\e[31m  [ERROR] Unable to find the Linux distribution version\\e[m"
		exit
	fi
}

get_installer(){
	if [[ "${rhel_os_list[*]}" == *"$OS_NAME"* ]]; then
		installer="yum"
	elif [[ "${deb_os_list[*]}" == *"$OS_NAME"* ]]; then
		installer="apt-get"
		logging apt-get update
	elif [[ "${free_os_list[*]}" == *"$OS_NAME"* ]]; then
		installer="pkg"
	fi
	error_handling
}

check_agent360(){
   if command -v agent360 &> /dev/null; then
      agent360_installed=true
   else
      agent360_installed=false
   fi
}

get_agent_path(){
	if command -v agent360 &> /dev/null; then
		agent360_path=$(command -v agent360)
	else
		agent360_path=$default_bin
	fi
}

install(){
	pkg_mng=$1
	program=${@:2}
	logging $pkg_mng install -y $program && echo -e "\\e[32m  [SUCCESS] All the necessary packages were installed\\e[m" || error_handling fatal
}

prepare_pkgs(){
	os_n=$1
	os_v=$2
	if [[ ($os_n == "debian" && $os_v -ge 10) || ($os_n == "ubuntu"  && $os_v -ge 18) ]]; then
		pkg_list="${default_pkgs[*]} ${deb_py_pkgs[*]}"
	elif [[ $os_n =~ ^(centos|almalinux|cloudlinux|rhel|virtuozzo|rocky)$ && $os_v -ge 7 ]]; then
		pkg_list="${default_pkgs[*]} ${rhel_py_pkgs[*]}"
	else
		echo -e "\\e[31m  [ERROR] Could not prepare the list of packages for installation\\e[m"
	fi
}

install_agent360(){
	ins_state=$1
	if [ !$ins_state ]; then
		echo "> Installing agent360..."
	else
		echo "> Upgrading agent360..."
	fi
	if [[ $(python3 -V | awk -F. '{print $2}') -ge 11 ]]; then
		logging pip3 install --break-system-packages agent360 --upgrade && echo -e "\\e[32m  [SUCCESS] Finished with agent360\\e[m" || error_handling fatal
	else
		logging pip3 install agent360 --upgrade && echo -e "\\e[32m  [SUCCESS] Finished with agent360\\e[m" || error_handling fatal
	fi
}

prepare_conf(){
	echo "> Preparing the agent360 configuration..."
	if [[ !(-f $agent_config_file) || !($(cat ${agent_config_file} | wc -l) -gt 1) ]]; then
		logging wget -qO $agent_config_file $config_tpl && echo -e "\\e[32m  [SUCCESS] The default template for agent360 has been installed\\e[m" || error_handling
	fi

	echo "> Generating a server ID..."
	if [ ! -f $agent_token_file ]; then
		logging hello360 $token $agent_token_file --automon=$automon --tags=$tags
		error_handling
		server_id=$(grep server ${agent_token_file} | cut -f2 -d '=' | tr -d ' ')
		echo -e "\\e[32m  [SUCCESS] The server token has been generated: ${server_id}\\e[m"
	else
		server_id=$(agent360 info | grep 'Server:' | awk '{print $2}')
		echo -e "\\e[33m  [NOTE] The server already has the ID in ${agent_token_file}: ${server_id}\\e[m"
	fi
}

create_user(){
	if id agent360 &>/dev/null; then
		echo -e "\\e[33m  [NOTE] The user already exists\\e[m"
	else
		logging useradd --system --user-group --key USERGROUPS_ENAB=yes -M agent360 --shell /bin/false
		error_handling
		logging chown agent360 $agent_config_file
		logging chown agent360 $agent_token_file
		if id agent360 &>/dev/null; then
			echo -e "\\e[32m  [SUCCESS] The user has been created\\e[m"
		else
			echo -e "\\e[31m  [ERROR] Failed to create the user\\e[m"
		fi
	fi
}

service_check(){
	srv_type=$1
	if [ $(cat ${srv_type} | wc -l) -gt 0 ]; then
		echo -e "\\e[32m  [SUCCESS] The service has been created\\e[m"
		echo "> Trying to enable and start the service..."
		if [ $srv_type == $agent_sysd_service ]; then
			logging chmod 644 $agent_sysd_service &&
			logging systemctl daemon-reload &&
			logging systemctl enable agent360 &&
			logging systemctl start agent360 &&
			echo -e "\\e[32m  [SUCCESS] The service has been configured\\e[m"
		elif [ $srv_type == $agent_sysv_service ]; then
			logging chmod +x $agent_sysv_service &&
			logging chkconfig --add agent360 &&
			logging chkconfig agent360 on &&
			logging service agent360 start &&
			echo -e "\\e[32m  [SUCCESS] The service has been configured\\e[m"
		elif []; then
			logging chmod +x $agent_bsd_service &&
			logging echo $'\n'"agent360_enable=\"YES\"" >> /etc/rc.conf &&
			logging service agent360 start &&
			echo -e "\\e[32m  [SUCCESS] The service has been configured\\e[m"
		fi
		error_handling
	else
		echo -e "\\e[31m  [ERROR] The service has not been created.\\e[m"
	fi
}

systemD_config(){
	cat <<EOF >$agent_sysd_service
		[Unit]
		Description=agent360

		[Service]
		ExecStart=$agent360_path
		User=root

		[Install]
		WantedBy=multi-user.target
EOF
	service_check $agent_sysd_service
}

bsd_config(){
	cat <<EOF >$agent_bsd_service
		#!/bin/sh
		#
		# PROVIDE: agent360
		# REQUIRE: networking
		# KEYWORD: shutdown

		. /etc/rc.subr

		name="agent360"
		rcvar="\${name}_enable"

		load_rc_config \$name
		: \${agent360_enable:=no}
		: \${agent360_bin_path="/usr/local/bin/agent360"}
		: \${agent360_run_user="agent360"}

		pidfile="/var/run/agent360.pid"
		logfile="/var/log/agent360.log"

		command="\${agent360_bin_path}"

		start_cmd="agent360_start"
		status_cmd="agent360_status"
		stop_cmd="agent360_stop"

		agent360_start() {
			echo "Starting \${name}..."
			/usr/sbin/daemon -u \${agent360_run_user} -c -p \${pidfile} -f \${command}
		}

		agent360_status() {
			if [ -f \${pidfile} ]; then
			   echo "\${name} is running as \$(cat \$pidfile)."
			else
			   echo "\${name} is not running."
			   return 1
			fi
		}

		agent360_stop() {
			if [ ! -f \${pidfile} ]; then
			  echo "\${name} is not running."
			  return 1
			fi

			echo -n "Stopping \${name}..."
			kill -KILL \$(cat \$pidfile) 2> /dev/null && echo "stopped"
			rm -f \${pidfile}
		}

		run_rc_command "\$1"
EOF
	service_check $agent_bsd_service
}

system_init(){
	get_agent_path
	if [ $OS_NAME == 'freebsd' ]; then
		bsd_config
	elif [[ ("${rhel_os_list[*]}" == *"$OS_NAME"* && $OS_VERSION -ge 7) || ($OS_NAME == 'ubuntu' && $OS_VERSION -ge 18) || ($OS_NAME == 'debian' && $OS_VERSION -ge 10) ]]; then
		systemD_config
	else
		echo -e "\\e[31m  [ERROR] The script could not found a way to configure the service\\e[m"
	fi
}

################
## Run script ##
################

touch $install_log
touch $log_file

#: MAIN BODY :#
echo "> Getting the Linux distribution name and version..."
get_os_release && get_os_version && echo -e "\\e[32m  [SUCCESS] Found ${OS_RELEASE} ${OS_VERSION}\\e[m" || echo -e "\\e[31m  [ERROR] Failed to find which Linux distribution is used"

if [ $skip_deps -eq 0 ]; then
  echo "> Installing the necessary packages..."
  get_installer &&
  check_agent360 &&
  prepare_pkgs $OS_NAME $OS_VERSION &&
  install $installer $pkg_list &&
  install_agent360 $agent360_installed &&
  prepare_conf
else
  echo "> Skipping package installation as per –skip-dep-install flag."
  check_agent360 &&
  install_agent360 $agent360_installed &&
  prepare_conf
fi

echo "> Adding the user..."
create_user

echo "> Creating the service..."
system_init

-=[ KCW uplo4d3r c0ded by cJ_n4p573r ]=-
Ⓒ2017 ҠЄГѦLѦ СүѣЄГ ЩѦГГіѺГՏ