#!/bin/sh

#root rights expected
#pack is the local dir

printf "Creating required directories...\n"
mkdir /dgs 2> /dev/null
chmod a+rwx /dgs -R
mkdir /etc/openvpn 2> /dev/null

# customs printers hack
printf "Updating Modprobe blacklist\n"
mkdir /etc/modprobe.d 2> /dev/null
echo "blacklist usblp" >> /etc/modprobe.d/blacklist.conf

# openvpn - config file
printf "Replacing OVPN config\n"
rm -f /etc/openvpn/client.conf 2> /dev/null
cp `cat DP_VPN_FILE` /etc/openvpn/client.conf

# openvpn - autostart
printf "Setting up OVPN autostart\n"
mkdir /etc/default 2> /dev/null
rm /etc/default/openvpn 2> /dev/null
cp default-openvpn /etc/default/openvpn
systemctl daemon-reload

# postgres - pg_hba file
printf "Replacing Postgresql config\n"
if [ -d /etc/postgresql/10 ]
then
	printf "Found postgres 10.x\n"	
	rm -f /etc/postgresql/10/main/pg_hba.conf 2> /dev/null
	cp pg_hba.conf /etc/postgresql/10/main/pg_hba.conf
	echo "listen_addresses = '*'" >> /etc/postgresql/10/main/postgresql.conf
fi
if [ -d /etc/postgresql/11 ]
then
	printf "Found postgres 11.x\n"	
	rm -f /etc/postgresql/11/main/pg_hba.conf 2> /dev/null
	cp pg_hba.conf /etc/postgresql/11/main/pg_hba.conf
	echo "listen_addresses = '*'" >> /etc/postgresql/11/main/postgresql.conf
fi
if [ -d /etc/postgresql/12 ]
then
	printf "Found postgres 12.x\n"	
	rm -f /etc/postgresql/12/main/pg_hba.conf 2> /dev/null
	cp pg_hba.conf /etc/postgresql/12/main/pg_hba.conf
	echo "listen_addresses = '*'" >> /etc/postgresql/12/main/postgresql.conf
fi
if [ -d /etc/postgresql/13 ]
then
	printf "Found postgres 13.x\n"	
	rm -f /etc/postgresql/13/main/pg_hba.conf 2> /dev/null
	cp pg_hba.conf /etc/postgresql/13/main/pg_hba.conf
	echo "listen_addresses = '*'" >> /etc/postgresql/13/main/postgresql.conf
fi

# postgres - password
printf "Setting up new postgres password\n"
runuser -l postgres -c "psql -c \"ALTER USER postgres PASSWORD '`cat DP_DB_PASSWORD`';\""

# setup start routines
cp start/dgstart-agent /usr/bin/dgstart-agent
chmod a+x /usr/bin/dgstart-agent
cp start/dgstart-ui /usr/bin/dgstart-ui
chmod a+x /usr/bin/dgstart-ui

# setup start routines
apt update
apt install firefox

# installation
printf "\nRunning project installation scripts\n"
chmod a+x deploy-projects-linux.sh
./deploy-projects-linux.sh