#!/bin/bash

PIDFILE="/var/run/nito.pid"

# Stop if it looks like there's already an agent installed/running
if [ -f ${PIDFILE} ]; then
	echo "NITO: Error 1:"
	echo "NITO: Cannot continue with installation because a Nito daemon may already be running on this system."
	echo -e "\t(if you know that Nito is not running, you can safely delete '/var/run/nito.pid' and try again.)"
	echo ""
	exit 1
fi

if [ $(echo "$UID") = "0" ]; then
    SUDO_IF_NOT_ROOT=''
else
    SUDO_IF_NOT_ROOT='sudo'
fi

echo "##################################################################"
echo "#                        __                                      #"
echo "#                       |__|                                     #"
echo "#           |‾‾‾‾‾\ |‾‾||‾‾||‾‾‾‾‾‾||‾‾|‾‾|‾‾|                   #"
echo "#           |  |\  \|  ||  | ‾|  |‾ |‾‾|‾‾|‾‾|                   #"
echo "#           |  | \     ||  |  |  |  |‾‾|‾‾|‾‾|                   #"
echo "#            ‾‾   ‾‾‾‾‾  ‾‾    ‾‾    ‾‾ ‾‾ ‾‾                    #"
echo "#                                                                #"
if [ $(grep -o "[\:]" <<<"${NITOREG}" | wc -l) -ne 1 ]; then
echo "# Install with your your username and the agent's temporary code #"
echo "#      (e.g. username@example.com:RandomTemporaryCode)           #"
fi
echo "##################################################################"

# Get registration code from user (if we don't already have it)
while [ $(grep -o "[\:]" <<<"${NITOREG}" | wc -l) -ne 1 ]
do
	echo -n "Enter the agent's registation string: "
	read NITOREG
	if [ "${NITOREG}" = "" ] ; then
		echo ""
		echo "Registration string not entered (or, if this message appeared without any interaction from you, you may be using an obsolete install command)"
		exit
	fi
	sleep 1
done

# Function for whitelisting only specific characters for URL
function nitourlencode {
	# only alphanumeric and []()-_./ | trim |  replace spaces and square-braces with url encoding or else curl will attempt to glob
	echo $@ | tr -c '[:alnum:]\[\]\(\)\-\_\.\/' ' ' | sed -e 's/^[ \t]*//' -e 's/[ \t]*$//' | sed -r 's/\s+/%20/g' | sed -r 's/\[+/%5B/g' | sed -r 's/\]+/%5D/g'
}

# Get OS/REV/ARCH (keep to only absolutely necessary characters, especially no ampersands)
if [ -f /etc/hostname ]; then
  REGHOSTNAME=$(nitourlencode $(cat /etc/hostname))
else
  REGHOSTNAME=$(nitourlencode $(hostname))
fi
REGOS=$(nitourlencode $(uname -s))
REGREV=$(nitourlencode $(uname -r))
REGARCH=$(nitourlencode $(uname -m))

if [ "${REGOS}" = "Linux" ] ; then
	# Get the linux VERSION_ID directly from /etc/os-release, or else mimic it
	if [ -e /etc/os-release ]; then
		. /etc/os-release
		if [ -z "${REGID}" ]; then
			REGID=$ID
		fi
		REGVERSION_ID=$VERSION_ID
	elif [ -e /etc/redhat-release ]; then
		REGVERSION_ID=$(cat /etc/redhat-release | sed s/.*release\ // | sed s/\ .*//)
	elif [ -e /etc/lsb-release ]; then
		. /etc/lsb-release
		REGID=$(echo ${DISTRIB_ID} | tr '[:upper:]' '[:lower:]')
		REGVERSION_ID=${DISTRIB_RELEASE}
	elif [ -e /etc/debian_version ]; then
		REGID='Debian'
		REGVERSION_ID=$(cat /etc/debian_version)
	fi
	REGVERSION_ID=$(nitourlencode ${REGVERSION_ID})
	
	# Get the Linux distribution type
	if [ -e /etc/redhat-release ] ; then
		REGDIST='RedHat'
	elif [ -e /etc/debian_version ] ; then
		if [[ ${REGID} == *"ubuntu"* ]]; then
			REGDIST='Ubuntu'
		elif [[ ${REGID} == *"debian"* ]]; then
			REGDIST='Debian'
		else
			REGDIST=${REGID}
		fi
	fi
	REGDIST=$(nitourlencode ${REGDIST})

	NITOFOLDER=$(nitourlencode ${NITOFOLDER})

	# Get the installation script embedded with the registration credentials
	echo "NITO: Starting installation..."
	#echo "https://repo.nito.net/nix-install-script?NITOFOLDER=${NITOFOLDER}&HOSTNAME=${REGHOSTNAME}&OS=${REGOS}&REV=${REGREV}&ARCH=${REGARCH}&VERSION_ID=${REGVERSION_ID}&DIST=${REGDIST}&DELAY_ACTIVATION=${DELAY_ACTIVATION}"
	$SUDO_IF_NOT_ROOT bash -c "$(cat <(curl -Ss -u ${NITOREG} "https://repo.nito.net/nix-install-script?NITOFOLDER=${NITOFOLDER}&HOSTNAME=${REGHOSTNAME}&OS=${REGOS}&REV=${REGREV}&ARCH=${REGARCH}&VERSION_ID=${REGVERSION_ID}&DIST=${REGDIST}&DELAY_ACTIVATION=${DELAY_ACTIVATION}"))"
else
	# Not an OS type that we support (i.e., not Linux)
	echo "Error 99:"
	echo "This OS type '${REGOS}' is not yet supported"
	echo ""
	exit 1
fi
