#!/bin/sh

#
# Bitdefender (c) 2021
#

# chkconfig: 2345 80 30
# description: Professional antivirus solution targeting datacenter wide protection

### BEGIN INIT INFO
# Provides:		antivirus
# Required-Start:	$syslog $remote_fs
# X-UnitedLinux-Should-Start: $time ypbind sendmail
# Required-Stop:	$syslog $remote_fs
# X-UnitedLinux-Should-Stop: $time ypbind sendmail
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	Bitdefender Security Tools
# Description:		Professional antivirus solution targeting
#			both servers and workstations
### END INIT INFO

set -e

BRAND="Bitdefender"
DIR="/opt/bitdefender-security-tools"
CONFIG="$DIR/etc/bdsecd.json"
ENABLE_GZ_INTEGRATION="ON"

LOCKDIR="/var/lock/subsys"
LOCKFILE="${LOCKDIR}/bdsec"

LC_ALL=C
export LC_ALL

BDINSTALLPATH="$DIR"
export BDINSTALLPATH

umask 0077

install_dazukofs ()
{
	local mode="$1"

	local kernel_release=$(uname -r)
	local kernel_arch=$(uname -m)
	local alt_kernel_release=$(echo "$kernel_release" | sed "s#\.$kernel_arch##")

	# if the module is already installed, skip all steps below
	[ -f "/lib/modules/${kernel_release}/kernel/fs/dazukofs/dazukofs.ko" ] && [ "$mode" = "install" ] && return 0

	# don't go through the motions if the module archive does not exist
	local modules_tgz="$DIR/var/lib/modules/dazukofs/base/dazukofs-modules.tar.gz"
	if [ -f "$DIR/var/lib/modules/dazukofs/update.jso" ]; then
		updidx=$($DIR/bin/jq -r ".id" "$DIR/var/lib/modules/dazukofs/update.jso")
		[ -f "$DIR/var/lib/modules/dazukofs/dazukofs_$updidx/dazukofs-modules.tar.gz" ] && \
			modules_tgz="$DIR/var/lib/modules/dazukofs/dazukofs_$updidx/dazukofs-modules.tar.gz"
	fi
	[ -f "$modules_tgz" ] || return 1

	# install the dazukofs module
	mkdir -p "$DIR/var/tmp/dazukofs"
	tar --no-same-owner -C "$DIR/var/tmp/dazukofs" -xzf "$modules_tgz"
	local ko_name="dazukofs-*-${kernel_release}_${kernel_arch}.ko"
	local module=$(find "$DIR/var/tmp/dazukofs" -type f -name "$ko_name" 2>/dev/null | head -n 1)
	if [ -n "$module" ]; then
		mkdir -p "/lib/modules/$kernel_release/kernel/fs/dazukofs" || true
		cp -f "$module" "/lib/modules/$kernel_release/kernel/fs/dazukofs/dazukofs.ko"
		depmod -a >/dev/null 2>&1 || true
	else
		ko_name="dazukofs-*-${alt_kernel_release}_${kernel_arch}.ko"
		module=$(find "$DIR/var/tmp/dazukofs" -type f -name "$ko_name" 2>/dev/null | head -n 1)
		if [ -n "$module" ]; then
			mkdir -p "/lib/modules/$kernel_release/kernel/fs/dazukofs" || true
			cp -f "$module" "/lib/modules/$kernel_release/kernel/fs/dazukofs/dazukofs.ko"
			depmod -a >/dev/null 2>&1 || true
		fi
	fi
	rm -rf "$DIR/var/tmp/dazukofs"
	[ -n "$module" ] || return 1
}

load_dazukofs ()
{
	local selinuxenabled=$(which selinuxenabled 2>/dev/null || true)
	if [ -n "$selinuxenabled" ]; then
		if $selinuxenabled 2>/dev/null; then
			# do not load the module if SELinux is enabled and set to 'enforcing'
			getenforce 2>/dev/null | grep -iq enforcing && return 0 || true
		fi
	fi
	modprobe dazukofs
}

# Check if the kernel is older than 2.6.37 when fanotify was enabled in the kernel
# after having been introduced in 2.6.36 (see fanotify(7))
check_fanotify ()
{
	local kver=$(uname -r | grep -E -o '^[0-9]+\.[0-9]+\.[0-9]+' || true)
	local kmajor=$(printf "$kver" | cut -d. -f 1)
	local kminor=$(printf "$kver" | cut -d. -f 1)
	local krelease=$(printf "$kver" | cut -d. -f 1)

	[ -z "$kver" ] && return 1

	[ $kmajor -gt 2 ] && return 0

	[ $kminor -gt 6 ] && return 0

	[ $krelease -gt 36 ] && return 0

	return 1
}

mount_amzn1_debugfs ()
{
	local arch=$(uname -m)
	[ "$arch" = "x86_64" ] || [ "$arch" = "aarch64" ] || return 0

	grep -qE 'ID="?amzn"?' /etc/os-release 2> /dev/null || return 0
	grep -qE 'VERSION_ID="201[78]' /etc/os-release 2> /dev/null || return 0

	! [ -x /bin/systemctl -o -x /usr/bin/systemctl ] || return 0

	[ ! -e /sys/kernel/debug/tracing/kprobe_events ] || return 0

	mount -t debugfs none /sys/kernel/debug 2> /dev/null
}

check_module ()
{
	local idx=$($DIR/bin/jq ".modules | map(.name == \"$1\") | index(true)" "$CONFIG")
	[ "$idx" = "null" ] && return 1
	local state=$($DIR/bin/jq -r ".modules[$idx].installed" "$CONFIG")
	[ "$state" = "false" ] && return 1
	return 0
}

start_daemon_impl ()
{
	local proc="$1"
	local name="$2"

	shift
	shift

	printf "Starting: $BRAND $name\n"
	cd /

	unset $(env | grep -E '^(\w+)=(.*)$' | cut -d= -f1 | grep -E -vw 'LANG|PATH|BDINSTALLPATH') 2>/dev/null
	PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"
	export PATH
	$DIR/bin/$proc $@ >/dev/null || true
}

start_daemon ()
{
	( start_daemon_impl "$@" )
}

stop_daemon_impl ()
{
	local proc="$1"
	local name="$2"

	shift
	shift

	printf "Stopping: $BRAND $name\n"
	cd /

	unset $(env | grep -E '^(\w+)=(.*)$' | grep -E -vw 'LANG|PATH|BDINSTALLPATH' | cut -d= -f1)
	PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"
	export PATH
	$DIR/bin/$proc $@ >/dev/null || pkill -9 "$proc"
}

stop_daemon ()
{
	( stop_daemon_impl "$@" )
}

is_container ()
{
	local container=$($DIR/bin/jq ".container" "$DIR/etc/bdsecd.json" 2>/dev/null || true)

	[ "$container" = "true" ] && return 0 || return 1
}

start_bd ()
{
	if is_container; then
		pkill -USR1 bdwatchdogd
		return $?
	fi

	check_fanotify || ( install_dazukofs update && load_dazukofs || printf "Error: failed to install the DazukoFS module for %s\n" "$(uname -r)" >&2 )

	mount_amzn1_debugfs || true

	start_daemon bdwatchdogd "Service Manager Daemon" -c "$DIR/etc/bdwatchdogd.json" -s

	[ -d "$LOCKDIR" ] && touch "$LOCKFILE" || true
}

stop_bd ()
{
	if is_container; then
		pkill -USR2 bdwatchdogd || return $?
		for d in epagngd updated bdsecd ausecd arrakis; do
			for i in $(seq 30); do
				pc=$(pgrep -c -x $d || true)
				[ $pc -eq 0 ] && break
				sleep 1
			done
		done
		return 0
	fi

	stop_daemon bdwatchdogd "Service Manager Daemon" -c "$DIR/etc/bdwatchdogd.json" -k

	for p in bdwatchdogd bdsecd updated epagngd ausecd arrakis; do
		pkill -KILL $p >/dev/null 2>&1 || true
	done

	rm -f "$LOCKFILE"
}

bdpidofproc ()
{
	local proc="${1}"
	local pidofPath

	if [ -x /sbin/pidof ]; then
		pidofPath=/sbin/pidof
	elif [ -x /bin/pidof ]; then
		pidofPath=/bin/pidof
	fi

	if [ ! -z $pidofPath ]; then
		$pidofPath "${proc}"
	else
		local ps
		ps=$(ps -wwax | awk "{if ( \\${0} ~ /${proc}/ && \\${0} !~ /awk/ ) printf \"%s \", \\${1} }")

		if [ -z "${ps}" ]; then
			return 1
		else
			echo "${ps}"
		fi
	fi
}

daemon_status ()
{
	local running=""
	local daemon="${1}"
	local descr="${BRAND} ${2}"
	local msg
	local pidf="${daemon}"

	if [ -x "${BDINSTALLPATH}/bin/${daemon}" ]; then
		# check to see if ${daemon} is already running
		local pids
		pids=$(bdpidofproc "${daemon}" 2>/dev/null) && running="yes" || unset running

		if [ -n "${running}" ]; then
			local diff=""
			local ls_output
			ls_output=$(ls -l --full-time "${BDINSTALLPATH}/var/run/${pidf}.pid" 2>/dev/null || true)
			if [ -n "$ls_output" ]; then
				local started_on
				started_on="$(echo "${ls_output}" | awk '{ i=6; while (i<NF) if ( $i !~ /^\// ) { time=time" "$i; i++; } else break; sub(/\.[0-9]+/,"",time); print time }')"

				started_on="$(date -d "${started_on}" +"%s" 2>/dev/null)"
				if [ ${?} -eq 0 ]; then
					diff=$(( $(date +"%s" 2>/dev/null) - started_on ))
					local days hours mins
				fi
			fi
			if [ -n "${diff}" ]; then
				[ ${diff} -ge 86400 ] && { days=$(( diff / 86400 )); diff=$(( diff - days * 86400 )); } || days=0
				[ ${diff} -ge 3600 ] && { hours=$(( diff / 3600 )); diff=$(( diff - hours * 3600 )); } || hours=0
				[ ${diff} -ge 60 ] && { mins=$(( diff / 60 )); diff=$(( diff - mins * 60 )); } || mins=0
				msg="(pid(s) ${pids}) running... for ${days}d ${hours}h ${mins}m ${diff}s"
			else
				msg="(pid(s) ${pids}) running..."
			fi
		else
			if [ ! -f "${BDINSTALLPATH}/var/run/${pidf}.pid" ]; then
				msg="not running."
			else
				msg="dead but pid file exists."
			fi
		fi

		echo "${descr} (${daemon}) ${msg}"
	fi
}

status_bd ()
{
	[ $ENABLE_GZ_INTEGRATION = "ON" ] && \
		daemon_status epagngd "Endpoint Agent Daemon"
	daemon_status bdsecd "Security Tools Daemon"
	daemon_status updated "Update Daemon"

	( check_module relay || check_module patchmanagementserver ) && \
		daemon_status arrakis "Update Server Daemon" || true
}

bd_invoke_systemctl ()
{
	local systemctl=$(which systemctl 2>/dev/null || true)
	if [ -n "$systemctl" ] && [ -z "$BDSYSCTL" ]; then
		# Certain container images (eg. Ubuntu 16.04, Rocky Linux 8) have systemd installed but unused.
		systemctl is-system-running | grep -Fqv offline || return 0

		if [ "$1" = "start" ] || [ "$1" = "stop" ] || [ "$1" = "restart" ]; then
			$systemctl "$1" bdsec
			[ "$1" = "stop" ] && $systemctl reset-failed bdsec-daemon || true
			exit 0
		elif [ "$1" = "status" ]; then
			local services="bdsec-daemon bdsec-update"
			[ $ENABLE_GZ_INTEGRATION = "ON" ] && \
				services="$services bdsec-epagng"
			( check_module relay || check_module patchmanagementserver ) && \
				services="$services bdsec-arrakis"
			$systemctl status $services || true
			exit 0
		fi
	fi
}

bd_invoke_systemctl "$@"

case "$1" in
	"start")
		start_bd
	;;
	"stop")
		stop_bd
	;;
	"restart")
		stop_bd
		start_bd
	;;
	"status")
		status_bd
	;;
esac
