#!/bin/bash
#
#**********************************
#Copyright © 2019 Dynimize, Inc.
#All rights reserved
#*********************************

wget -qO- https://dynimize.com/dyniDownloadCounter.php?state=0 &> /dev/null

function checkCmd
	{
	if [ $? -ne 0 ]; then
        	echo Installation FAILED 
        	exit 1
	fi
	}

function quickStart
	{
echo "


Quickstart:

To obtain an access token, sign up for an account at https://dynimize.com/signup


Start a license on this host:

$ sudo dyni -license=start -token=<access token>


Start Dynimize:

$ sudo dyni -start

If running a CPU intensive process who's exe is under [exeList] in
/etc/dyni.conf, Dynimize will automatically begin optimizing it.

WARM UP PERIOD: The optimization phase may temporarily increase
the CPU usage of the target process and temporarily reduce performance.
This phase can last anywhere from 30 seconds to several minutes. The 
more CPU intensive the target process, the faster it will become
optimized by Dynimize, and the shorter this phase will be.

The command dyni -status will show target processes progressing
from the 'profiling' to 'dynimizing', and then 'dynimized' states. 
A process has been fully optimized once in the 'dynimized' state:

$ sudo dyni -status

Dynimize is running
mysqld, pid: 8375, dynimizing


$ sudo dyni -status

Dynimize is running
mysqld, pid: 8375, dynimized


Shutdown Dynimize:

$ sudo dyni -stop


Remove the optimizations:

$ sudo dyni -undo


Stop the license on this host:

$ sudo dyni -license=stop -token=<access token>


See https://dynimize.com/measure for help measuring the performance impact."
	}

function printInstallComplete
	{
	quickStart;

	echo "


Feedback, bug reports and questions can be emailed to support@dynimize.com.	

A copy of the accepted End User License Agreement can be found in the file
LICENSE. A copy of the accepted Terms of Use can be found in the file TERMS.

Dynimize installation is complete.
"
	}

acceptMsg="THE END USER LICENSE AGREEMENT CAN BE FOUND AT:
https://dynimize.com/legal/dyni-eula

THE TERMS OF USE CAN BE FOUND AT:
https://dynimize.com/legal/dyni-terms-of-use

DO YOU ACCEPT THE TERMS OF THE END USER LICENSE AGREEMENT, AND TERMS OF USE?
"

function fail 
	{
	echo $1
	echo Installation failed. > /dev/tty
        exit 1
        }

function getYN
	{
	default=$2
	question=$1
	strict=$3

	if [ "$default" = "yes" ]; then
		result=1
	else
		result=0
	fi

   	if [ "$strict" = "strict" ]; then
		read -p "$question[default: $default] (yes/no) " choice

	        case "$choice" in
                	yes|YES|Yes ) result=1;;
                	n|N|no|NO|No ) result=0;;
	        esac
        else
		read -p "$question[default: $default] (y/n) " choice

		case "$choice" in
                	y|Y|yes|YES|Yes ) result=1;;
               	 	n|N|no|NO|No ) result=0;;
        	esac
        fi

	if [ $result -eq 1 ]; then
        	echo yes > /dev/tty
	else
        	echo no > /dev/tty
	fi

	echo $result
	}

function writeConfig
	{
	launchAtStart=$1
	#setup config file
	config=/etc/dyni.conf

	echo Writing configuration file $config

	rm -rf $config
	echo "#One option per line" >> $config

	if [ $? -eq 1 ]; then
		fail "Couldn't write to configuration file /etc/dyni.conf"
	fi

	chmod 600 /etc/dyni.conf
	echo "[options]" >> $config
	echo log=/var/log/dyni.log >> $config
	echo maxLogSize=1MB >> $config
	echo ""
	echo "#initdService makes dyni start on OS startup." >> $config
	echo "initdService" >> $config
	echo ""
	echo "#reoptimize" >> $config

	#echo sharedMem: n >> $config 

	echo >> $config
	echo "#The 'token' field in this file will get set to" >> $config
	echo "#any value passed into dyni -token=<val>" >> $config
	echo "token=12345" >> $config
	echo "autoRenew" >> $config
	echo "#autoUpdate" >> $config

	echo >> $config
	echo "#Case sensitive list of the executable file names of the processes to optimize" >> $config
	echo "#Each name separated with white space or new lines" >> $config
	echo "[exeList]" >> $config
	echo mysqld >> $config
	echo mariadbd >> $config
	echo " " >> $config
	echo "#[users]" >> $config
	echo "#mysql" >> $config
	}

function setupInitd
	{
        echo writing /etc/init.d/dyni
        cp ./dyni.initd /etc/init.d/dyni
        chmod a+x /etc/init.d/dyni


        if which update-rc.d > /dev/null 2>&1; then
                echo update-rc.d dyni defaults 0
                update-rc.d dyni defaults 0
        elif which chkconfig > /dev/null 2>&1; then
                chkconfig --add dyni
        fi
	}

function helper
	{
	echo Error parsing install script argument: $1 
	echo Possible arguments:
	echo "-acceptLicense:<yes|no>	
             DO YOU ACCEPT THE TERMS OF THE END USER LICENSE AGREEMENT AT 
             https://dynimize.com/legal/dyni-eula AND THE TERMS OF USE AT 
             https://dynimize.com/legal/dyni-terms-of-use ?"
	fail
	}

skipLaunchAtStart=0
acceptLicense=0
launchAtStart=0
skipAcceptLicense=0
fileName="dynimize-1-1-3-38-ga"

function processArg
	{
        if [ "$1" = "-acceptLicense:yes" ]; then
		acceptLicense=1
		skipAcceptLicense=1
		echo $acceptMsg
                echo "yes"
        elif [ "$1" = "-acceptLicense:no" ]; then
                acceptLicense=0
		skipAcceptLicense=1
                echo $acceptMsg 
		echo "no"
        elif [ "$1" = "-default" ]; then
                default=1
                echo "Default options selected."
        elif [ "$1" = "-d" ]; then
                default=1
                echo "Default options selected."
        else
                helper $1
	fi
	}

echo

for arg in "$@"
do
        echo "arg: $arg" 
        processArg $arg
done

# Make sure user is root 
if [ $UID -ne 0 ]; then
	fail "This script must be run as root."
fi

dyni -stop > /dev/null 2>&1

if [ $skipAcceptLicense = 0 ]; then
        echo "BEFORE PROCEEDING, PLEASE CAREFULLY READ OVER THE END USER LICENSE AGREEMENT AND
THE TERMS OF USE.
" 
        acceptLicense=$(getYN "$acceptMsg" "no" "not strict")
fi

if [ $acceptLicense -ne 1 ]; then
        echo Must accept the End User License Agreement, and Terms of Use to complete installation. Installation aborted.
        exit 1
fi

echo "Creating /opt/dynimize/ directory"
mkdir -p /opt/dynimize/status
checkCmd
cd /opt/dynimize/
checkCmd

wget -qO- https://dynimize.com/dyniDownloadCounter.php?state=1 &> /dev/null

#read -p "Please enter your email address: " email
#echo 
#wget -qO- "https://dynimize.com/dyniDownloadCounter.php?state=2&email=$email" &> /dev/null
wget https://dynimize.com/I_ACCEPT_TERMS_OF_THE_LICENSE_AND_THE_TERMS_OF_USE/$fileName.tar.gz -O $fileName.tar.gz
checkCmd
wget https://dynimizecloud.com/$fileName.tar.gz.sha256 -O $fileName.tar.gz.sha256
checkCmd

echo sha256sum -c $fileName.tar.gz.sha256
sha256sum -c $fileName.tar.gz.sha256 
checkCmd


echo "Extracting $fileName.tar.gz:"
tar -xvf ./$fileName.tar.gz
checkCmd

cp $fileName/* .
checkCmd
rm -rf $fileName* 
chmod 700 /opt/dynimize/measureDyniMysql

if [ -d "/etc/cron.weekly/" ]; then
        echo cp ./cron /etc/cron.weekly/dyni
        cp ./cron /etc/cron.weekly/dyni
        checkCmd
        chmod a+x /etc/cron.weekly/dyni
        checkCmd
elif [ -d "/etc/cron.monthly/" ]; then
        echo cp ./cron /etc/cron.monthly/dyni
        cp ./cron /etc/cron.monthly/dyni
        checkCmd
        chmod a+x /etc/cron.monthly/dyni
        checkCmd
fi

echo
echo Default installation options selected.
echo Launch Dynimize automatically on system startup? yes 
launchAtStart=1
setupInitd
writeConfig $launchAtStart 
echo " never_dynimized " > /opt/dynimize/status/journey
checkCmd
echo Estimated disk space required for installation: 1.14 MB    
echo cp ./dyni /usr/sbin
cp ./dyni /usr/sbin/
checkCmd
chmod a+x /usr/sbin/dyni
checkCmd
printInstallComplete
exit 0
