#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

sudo apt-get update
sudo apt-get install curl gnupg mutt cron netcat jq zip -y
#install yarn
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

sudo apt-get update && sudo apt-get install yarn -y
#install chrome
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo apt install ./google-chrome-stable_current_amd64.deb
rm ./google-chrome-stable_current_amd64.deb

# Create the configuration file for automated testing

read -n 1 -p "Create configuration file for automated testing (y/n)?" yesNo
if [ "$yesNo" != "n" ]; then
read -p "
Location of the apt file for ox (default /etc/apt/sources.list.d/open-xchange.list): " aptLocation
if [ "$aptLocation" = "" ]; then
	aptLocation="/etc/apt/sources.list.d/open-xchange.list"	
fi
defaultGitPath=$(realpath "$DIR/../..")
read -p "
Location of the guard git repo (default "$defaultGitPath")" gitPath
if [ "$gitPath" = "" ]; then
	gitPath=$defaultGitPath
fi
read -p "
From address for notification emails: " fromEmail
read -p "
Recipients for notification emails (comma separated list): " toEmails
read -p "
External IP for this machine for report link: " extIP

echo "gitDir=\""$gitPath"\"
tmpFile=\"/tmp/lastGit\"
aptFile=\""$aptLocation"\"
FROM=\""$fromEmail"\"
TO=\""$toEmails"\"
EXTIP=\""$extIP"\"
" > .testConfig

fi

# Setup CRON job for automated testing
script="$DIR/testGuard"
read -n 1 -p "
Create cron job to test Guard at midnight when git changes detected? (y/n) " yesNo
echo

if [ "$yesNo" != "n" ]; then
	sudo crontab -l > tempCron
	cronData=$(cat tempCron)
	if [[ $cronData =~ $script ]]; then
		echo "Script already in cron"
	else
		echo "00 00 * * * $script" >> tempCron
		sudo crontab tempCron
	fi
	rm tempCron


fi

# Setup the UI testing

ENVFILE="$DIR/../.env"
if [[ ! -f $ENVFILE ]]; then
	echo "UI test configuration file doesn't exist
	"
	read -n 1 -p "Create .env file for the UI tests? (y/n) " yesNo
	if [ "$yesNo" != "n" ]; then
		echo

		read -p "IP Address of the machine to test: " ip
		read -p "Context ID to use with testing: " cid
		read -p "FileStoreID to use with context: " filestore
		read -p "Domain for local email: " mxdomain
		DATA="PROVISIONING_URL=http://$ip/\nCONTEXT_ID=$cid\nLAUNCH_URL=http://$ip/appsuite/\nHEADLESS=true\nFILESTORE_ID=$filestore\nMX_DOMAIN=$mxdomain\n
"
		echo -e $DATA >> $ENVFILE 
		echo "Minimal .env file created.  Check .env-example for more options"
	fi
fi

# Setup HTML reports
if [[ ! -d /var/www/html/report ]]; then
	read -n 1 -p "Create symlink in var/www/html for reports (y/n) " yesNo
	if [ "$yesNo" != "n" ]; then
		ln -s $gitPath/oxguard-ui/allure-report /var/www/html/report
		echo "Symlink to $gitPath/oxguard-ui/allure-report made
		"
	fi
fi
