#!/bin/bash

FIRSTRUN=0
if [ -f "/etc/mocha/username" ]; then
	MOCHA_USERNAME=$(cat /etc/mocha/username)
	MOCHA_PASSWORD=$(cat /etc/mocha/userpass)
else
	# we are running for the first time (or we are transient)
	HTML_HOME=/var/www/html
	
	# reset the configuration file
	cp /etc/mocha/include/Configuration.inc.php.template $HTML_HOME/include/Configuration.inc.php
	
	# generate a not-very-secure but easily-rememberable password for zq-developer
	MOCHA_USERNAME="zq-developer"
	MOCHA_PASSWORD=$(pwgen -N 1)

        if [ ! $? -eq 0 ]; then
                echo ""
                echo "could not generate a secure password, you may need to (re-)install pwgen"
                echo ""
                exit 3
        fi

	echo $MOCHA_USERNAME > /etc/mocha/username
	echo $MOCHA_PASSWORD > /etc/mocha/userpass

	MOCHA_DB_DATABASENAME="mocha_suv"
	MOCHA_DB_USERNAME="mocha_suv"
	
	# also generate a slightly more secure machine password for the mariadb database...
	MOCHA_DB_PASSWORD=$(pwgen -s 32 -N 1)
	# ... and add it to the configuration file
	sed -i -e "s/@@MOCHA_DB_DATABASENAME@@/$MOCHA_DB_DATABASENAME/" -e "s/@@MOCHA_DB_USERNAME@@/$MOCHA_DB_USERNAME/" -e "s/@@MOCHA_DB_PASSWORD@@/$MOCHA_DB_PASSWORD/" $HTML_HOME/include/Configuration.inc.php

	# ... and also add it to our local configuration
	echo $MOCHA_DB_DATABASENAME > /etc/mocha/dbname
	echo $MOCHA_DB_USERNAME > /etc/mocha/dbuser
	echo $MOCHA_DB_PASSWORD > /etc/mocha/dbpass

	# don't forget to make a backup
	cp $HTML_HOME/include/Configuration.inc.php $HTML_HOME/include/Configuration.inc.php.bak

    # create the MySQL database and user with the previously generated password
    mysql -e "DROP DATABASE IF EXISTS $MOCHA_DB_DATABASENAME; DROP USER IF EXISTS $MOCHA_DB_USERNAME;"
	mysql -e "CREATE DATABASE $MOCHA_DB_DATABASENAME; CREATE USER $MOCHA_DB_USERNAME IDENTIFIED BY '$MOCHA_DB_PASSWORD'; GRANT ALL ON $MOCHA_DB_DATABASENAME.* TO '$MOCHA_DB_USERNAME'@'%';"

    # install mocha using the `mocha oms` command
	mocha oms install
	mocha oms install library /usr/share/mocha/libraries

	mocha oms tenant select super
	
	# set the new user name and password for the initial mocha user
	mocha oms user set-password "$MOCHA_USERNAME" "$MOCHA_PASSWORD"

	mocha oms tenant release
    
	# record the initial start time for the SUV
	echo $(date "+%Y-%m-%dT%H:%M:%S") > /etc/mocha/suvstart
	chmod a+r /etc/mocha/suvstart

	FIRSTRUN=1
fi

echo ""
echo "******************************************"
echo ""
echo "Thank you for provisioning your Mocha SUV!"
echo "You can log in with the following details:"
echo ""
echo "User name:     $MOCHA_USERNAME"
echo "Password:      $MOCHA_PASSWORD"
echo ""
echo "Your domain and IP address information is:"
echo ""
echo "    $(hostname).privatesuv.com"
ip addr show dev enp0s8 | grep inet
echo ""
echo "******************************************"
echo ""

if [ $FIRSTRUN -eq 1 ]; then
	# register the SUV for automatic shutdown in 10 hours
	/usr/lib/mocha/spot_register_for_shutdown 600
fi
