#!/usr/bin/bash
#
# Author: Scott R. Shinn <scott@atomicorp.com>
# https://www.atomicorp.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the Affero GNU General Public License (AGPL)
#

VERSION=6.2.0
GVM_VERSION=26.43

# Functions

# Input validation function 
# check_input <msg> <valid responses regex> <default>
# if <default> is passed on as null, then there is no default
# Example: check_input  "Some question (yes/no) " "yes|no"  "yes"
function check_input {
  message=$1
  validate=$2
  default=$3

  while [ $? -ne 1 ]; do
    echo -n "$message "
    read INPUTTEXT < /dev/tty
    if [ "$INPUTTEXT" == "" -a "$default" != "" ]; then
      INPUTTEXT=$default
      return 1
    fi
    echo $INPUTTEXT | egrep -q "$validate" && return 1
    echo "Invalid input"
  done
}

function download_update() {
	RETRIES=0
	DOWNLOAD_SUCCESS=0
	COMMAND=$1
	TEST=$2
	MSG=$3
	

	echo "$COMMAND"

	while [ $DOWNLOAD_SUCCESS -lt 1 ]; do
		if [ $RETRIES -gt 50 ]; then
			echo "Download not successful: too many failed attempts"
			echo "  rerun  $COMMAND manually"
			return 
		fi

		su - gvm -c "$COMMAND"

		if compgen -G "$TEST" > /dev/null 2>&1 || [ -e "$TEST" ]; then
			echo "$COMMAND success"
			DOWNLOAD_SUCCESS=1
		else
			echo "Retrying in 60 seconds..."
			sleep 60
			RETRIES=$(( $RETRIES + 1 ))
		fi
	done

}


echo
echo "#####################################"
echo "GVM Setup, Version: $VERSION"
echo "Atomicorp, Inc."
echo "#####################################"
echo 

# Test for selinux
if [ -f /usr/sbin/getenforce ]; then
SELINUX=$(getenforce 2>/dev/null)
	if [ $? -eq 0 ] ; then
		if [ "$SELINUX" != "Disabled" ] && [ "$SELINUX" != "Permissive" ]; then
			echo "Error: Selinux is set to ($SELINUX)"
			echo "  selinux must be disabled or permissive in order to use openvas"
			echo "  exiting...."
			exit 1
		fi
	fi
fi

# Ensure gvm system user exists and has a login shell for setup commands
if ! id gvm >/dev/null 2>&1; then
	useradd -r -m -d /var/lib/gvm -s /bin/bash -c "GVM (OpenVAS) User" gvm
else
	usermod -s /bin/bash gvm 2>/dev/null || true
fi

# Ensure directories exist with proper ownership
mkdir -p /var/lib/gvm/.ssh /var/lib/openvas /var/log/gvm /var/lib/notus /etc/openvas
chmod 700 /var/lib/gvm/.ssh 2>/dev/null || true
chown -R gvm:gvm /var/lib/gvm /var/lib/openvas /var/log/gvm /var/lib/notus 2>/dev/null || true

# Python 
if alternatives --list 2>/dev/null | grep -q '^python\b'; then
	alternatives --set python /usr/bin/python3 2>/dev/null || true
fi

# Set up postgres
if [ ! -f /var/lib/pgsql/initdb_postgresql.log ] && [ ! -f /var/lib/pgsql/data/PG_VERSION ]; then
	postgresql-setup --initdb --unit postgresql
fi

systemctl enable postgresql
systemctl start postgresql

if ! su - postgres -c "psql -tAc \"SELECT 1 FROM pg_roles WHERE rolname='gvm'\"" 2>/dev/null | grep -q 1; then
	su - postgres -c "createuser -DRS gvm"
fi
if ! su - postgres -c "psql -lqt" 2>/dev/null | cut -d \| -f 1 | grep -qw gvmd; then
	su - postgres -c "createdb -O gvm gvmd"
	su - postgres -c "psql gvmd -q --command='create role dba with superuser noinherit;'"
	su - postgres -c "psql gvmd -q --command='grant dba to gvm;'"
	su - postgres -c "psql gvmd -q --command='create extension \"uuid-ossp\";'"
	su - postgres -c "psql gvmd -q --command='create extension \"pgcrypto\";'"
	su - postgres -c "psql gvmd -q --command='create extension \"pg-gvm\";'"
	systemctl restart postgresql
fi




# redis / valkey setup
KV_SERVICE=""
KV_CONF=""
KV_GROUP=""
KV_SOCK=""

if [ -f /etc/valkey/valkey.conf ]; then
	KV_SERVICE="valkey"
	KV_CONF="/etc/valkey/valkey.conf"
	KV_GROUP="valkey"
	KV_SOCK="/run/valkey/valkey.sock"
elif [ -f /etc/valkey.conf ]; then
	KV_SERVICE="valkey"
	KV_CONF="/etc/valkey.conf"
	KV_GROUP="valkey"
	KV_SOCK="/run/valkey/valkey.sock"
elif [ -f /etc/redis/redis.conf ]; then
	KV_SERVICE="redis"
	KV_CONF="/etc/redis/redis.conf"
	KV_GROUP="redis"
	KV_SOCK="/run/redis/redis.sock"
elif [ -f /etc/redis.conf ]; then
	KV_SERVICE="redis"
	KV_CONF="/etc/redis.conf"
	KV_GROUP="redis"
	KV_SOCK="/run/redis/redis.sock"
else
	echo "Error: Neither Redis nor Valkey configuration was detected"
	exit 1
fi

mkdir -p "$(dirname "$KV_SOCK")"
chown "$KV_GROUP:$KV_GROUP" "$(dirname "$KV_SOCK")" 2>/dev/null || true

if ! grep -q "^unixsocket $KV_SOCK" "$KV_CONF" ; then
	sed -i -e "s|^\(#.\)\?unixsocket /.*$|unixsocket $KV_SOCK|" "$KV_CONF"
	if ! grep -q "^unixsocket " "$KV_CONF"; then
		echo "unixsocket $KV_SOCK" >> "$KV_CONF"
	fi
fi

if grep -q "unixsocketgroup" "$KV_CONF"; then
	sed -i -E "s/^#?\s*unixsocketgroup.*/unixsocketgroup $KV_GROUP/" "$KV_CONF"
else
	echo "unixsocketgroup $KV_GROUP" >> "$KV_CONF"
fi

if grep -q "unixsocketperm" "$KV_CONF"; then
	sed -i -E "s/^#?\s*unixsocketperm.*/unixsocketperm 770/" "$KV_CONF"
else
	echo "unixsocketperm 770" >> "$KV_CONF"
fi

sed -i -E "s/^#?\s*port [0-9]+/port 0/" "$KV_CONF"

# Bugfix for openvas (temporary)
sed -i "s/^save/#save/g" "$KV_CONF"

mkdir -p /etc/openvas
if grep -q ^db_address /etc/openvas/openvas.conf 2>/dev/null; then
	sed -i -e "s|^db_address=.*$|db_address=$KV_SOCK|" /etc/openvas/openvas.conf
else
	echo "db_address=$KV_SOCK" >> /etc/openvas/openvas.conf
fi

# Compatibility symlink for tools hardcoded to /run/redis/redis.sock
mkdir -p /run/redis
ln -sf "$KV_SOCK" /run/redis/redis.sock

if grep -q "databases" "$KV_CONF"; then
	sed -i -E "s/^#?\s*databases [0-9]+/databases 512/" "$KV_CONF"
else
	echo "databases 512" >> "$KV_CONF"
fi 

# Add user to redis/valkey socket group
if ! groups gvm 2>/dev/null | grep -q "$KV_GROUP" ; then
	usermod -aG "$KV_GROUP" gvm
fi

systemctl enable "$KV_SERVICE"
systemctl restart "$KV_SERVICE"

#Set sysctl
sysctl -w net.core.somaxconn=1024
sysctl vm.overcommit_memory=1
#
if ! grep -q "net.core.somaxconn=1024" /etc/sysctl.conf; then
	echo "net.core.somaxconn=1024"  >> /etc/sysctl.conf
fi
if ! grep -q "vm.overcommit_memory=1" /etc/sysctl.conf; then
	echo "vm.overcommit_memory=1" >> /etc/sysctl.conf
fi

#Disable transparent hugepages
if ! $(grub2-editenv - list | grep -q transparent_hugepage=never) ; then
	grub2-editenv - set "$(grub2-editenv - list | grep kernelopts) transparent_hugepage=never"
fi



# Download NVT updates
echo
echo "Update NVT, CERT, and SCAP data"
echo "Please note this step could take some time."
echo "Once completed, this will be updated automatically every 24 hours"
echo

FEED_SYNC="$(command -v greenbone-feed-sync 2>/dev/null || echo /usr/bin/greenbone-feed-sync)"

echo
echo "Updating NVTs...." 
download_update "$FEED_SYNC --type nvt" /var/lib/openvas/plugins/plugin_feed_info.inc

echo
echo "Updating GVMD_DATA..."
download_update "$FEED_SYNC --type gvmd-data" /var/lib/gvm/data-objects/gvmd/timestamp

echo
echo "Updating SCAP data..."
download_update "$FEED_SYNC --type scap" /var/lib/gvm/scap-data/timestamp


echo
echo "Updating CERT data..."
download_update "$FEED_SYNC --type cert"  /var/lib/gvm/cert-data/timestamp


su - gvm -c "openvas --update-vt-info"


# Handle certs
echo
echo -n "Updating OpenVAS Manager certificates: "
su - gvm -c "/usr/bin/gvm-manage-certs -V >/dev/null 2>&1"
if [ $? -ne 0 ]; then
	su - gvm -c "/usr/bin/gvm-manage-certs -a  >/dev/null 2>&1"
	echo "Complete"
else
	echo "Already Exists"
fi
echo


# Start ospd
systemctl enable ospd-openvas
systemctl restart ospd-openvas

# Start gvmd
systemctl enable gvmd
systemctl restart gvmd 

if ! compgen -G "/var/lib/gvm/data-objects/gvmd/*/timestamp" >/dev/null 2>&1 && [ ! -f /var/lib/gvm/data-objects/gvmd/timestamp ]; then
	echo "Error: GVMD Private data not found. "
	echo "  exiting..."
	exit 1
fi


echo -n "GVMD startup: "
until $(su - gvm -c "/usr/sbin/gvmd --get-users" >/dev/null 2>&1); do
 	echo -n .
        sleep 3 
done    
echo Done

if ! $(su - gvm -c "/usr/sbin/gvmd --get-users | grep -q ^admin$") ; then




	# Configure Admin user
	echo 
	echo "Set the GSAD admin users password."
	echo "The admin user is used to configure accounts,"
	echo "Update NVT's manually, and manage roles."
	echo 

	USERNAME=admin

	if [ -n "$ADMIN_PASSWORD" ]; then
		PASSWORD="$ADMIN_PASSWORD"
	else
		# Suppress output of password.
		if [[ -t 0 ]]; then
			stty -echo
		fi

		# Prompt the user for the desired password and verify its accuracy.  
		PASSCONFIRMED=0
		while [ $PASSCONFIRMED -lt 1 ]; do
			read -s -p "Enter Administrator Password: " PASSWORD
			echo

			read -s -p "Verify Administrator Password: " PASSWORD2
			echo


			if [ "$PASSWORD" == "$PASSWORD2" ]; then
				if [ "$PASSWORD" == "" ]; then
					echo "Empty password not allowed."
					PASSCONFIRMED=0
				else
					PASSCONFIRMED=1
				fi
				echo
			else
				echo "Passwords do not match"
				echo
			fi
		done
		stty echo
	fi


	# Create admin user
	su - gvm -c "/usr/sbin/gvmd  --create-user=${USERNAME}>/dev/null 2>&1"
	su - gvm -c "/usr/sbin/gvmd  --user=${USERNAME} --new-password=\"${PASSWORD}\""

	# Set the feed owner
	FEED_OWNER=$(su - gvm -c "/usr/sbin/gvmd --get-users --verbose" | awk '/^admin / {print $2}')
	if [[ $FEED_OWNER == "" ]]; then
		echo "Error: Feed owner could not be found"
		exit 1
	fi
	su - gvm -c "/usr/sbin/gvmd --modify-setting 78eceaec-3385-11ea-b237-28d24461215b --value $FEED_OWNER"

	# Load scan configs, port lists, and report formats from feed
	su - gvm -c "/usr/sbin/gvmd --rebuild-gvmd-data=all >/dev/null 2>&1 || true"

fi

# Mosquitto setup
mkdir -p /etc/openvas
if ! grep -q mqtt_server_uri /etc/openvas/openvas.conf; then
	echo "mqtt_server_uri = localhost:1883" >> /etc/openvas/openvas.conf
fi

# Configure GSAD systemd override for TLS and external access
mkdir -p /etc/systemd/system/gsad.service.d
cat << 'EOF' > /etc/systemd/system/gsad.service.d/override.conf
[Service]
ExecStart=
ExecStart=/usr/sbin/gsad --foreground --listen 0.0.0.0 --port 9392 -k /var/lib/gvm/private/CA/serverkey.pem -c /var/lib/gvm/CA/servercert.pem
EOF
systemctl daemon-reload

systemctl enable mosquitto
systemctl restart mosquitto
systemctl enable gsad
systemctl restart gsad
systemctl start notus-scanner 2>/dev/null || true
systemctl enable notus-scanner 2>/dev/null || true

# Set firewall rules
if command -v firewall-cmd >/dev/null 2>&1 && systemctl is-active firewalld >/dev/null 2>&1; then
	DEFAULT_ZONE=$(firewall-cmd --get-default-zone 2>/dev/null || echo "public")
	firewall-cmd --zone=$DEFAULT_ZONE --permanent --add-port=9392/tcp >/dev/null 2>&1 || true
	firewall-cmd --zone=$DEFAULT_ZONE --permanent --add-service=https >/dev/null 2>&1 || true
	firewall-cmd --zone=$DEFAULT_ZONE --permanent --add-forward-port=port=443:proto=tcp:toport=9392 >/dev/null 2>&1 || true
	firewall-cmd --reload >/dev/null 2>&1 || true
fi

# Planned, this is not multi-run safe yet
#if ! grep -q "Updating CERT info succeeded" /var/log/gvm/gvmd.log; then
#	echo "GVMD startup can take some time to complete. Please be patient"
#	echo
#	echo -n "GVMD initializing: "
#	COUNTER=0
#	tail -f /var/log/gvm/gvmd.log | while read LOGLINE; do
#		if [ $COUNTER -ge 600 ]; then
#			echo "Error: gvmd startup was not detected successfully"
#			echo "  exiting..."
#			exit 1
#		 fi
#
#		 if [[ "${LOGLINE}" == *"sync_cert: Updating CERT info succeeded"* ]]; then
#			echo "Complete"
#			break
#		 else
#			echo -n .
#		 fi
#
#		((COUNTER++))
#	done
#fi



echo
echo
echo "#####################################"
echo "Setup complete"
echo "  Log in to GSAD at https://localhost"
echo "#####################################"
echo
echo

# End

