#!/bin/sh

# This program is Copyright (c) 2013 VividCortex, Inc. All rights reserved.

VERSION=1.4.105

baseuri="https://download.vividcortex.com"
globalconf=/etc/vividcortex/global.conf
confdir="$(dirname "$globalconf")"
logdir=/var/log/vividcortex
tempdir=""
initdir=""


msg()
{
	echo "$1" >&2
}

abort()
{
	[ -n "$1" ] && msg "$1"
	[ -n "$tempdir" ] && rm -Rf "$tempdir"
	exit 1
}

createdir()
{
	mkdir -p "$1" || abort "Unable to create directory $1"
}

getfile()
{
	if which curl > /dev/null 2>&1; then
		curl -f -s "$1" > "$2" && return 0
	elif which wget > /dev/null 2>&1; then
		wget -q -O - "$1" > "$2" && return 0
	else
		abort "No suitable tool for file download found"
	fi

	abort "Unable to retrieve $1"
}



set -u
POSIXLY_CORRECT=1
export POSIXLY_CORRECT

if [ $(id -u) -ne 0 ]; then
	abort "This script must be run as root"
fi

longbit="$(getconf LONG_BIT) 2>/dev/null"
if [ -z "$longbit" ]; then
	if /usr/bin/file /bin/cat | grep 64.bit >/dev/null 2>&1; then
		longbit=64
	fi
fi
if [ "${longbit:-32}" = 32 ]; then
	abort "VividCortex isn't supported on 32-bit systems"
fi

echo -n "Please enter your VividCortex API token: "

if ! read VCTOKEN; then
	echo
	abort "Unable to read API token."
fi

if [ -z "$VCTOKEN" ]; then
	abort "A token has to be provided."
fi

echo

platform=$(uname -s | tr A-Z a-z)
distro=""
arch=""
initver=""

case "${platform}" in
	linux)
		initdir="/etc/init.d"

		if grep -i ubuntu /etc/*-release >/dev/null 2>&1 ; then
			distro="Ubuntu"
			initver="Debian"
		elif grep -i debian /etc/*-release >/dev/null 2>&1 ; then
			distro="Debian"
			initver="Debian"
		elif grep -i amazon /etc/*-release >/dev/null 2>&1 ; then
			distro="Amazon"
			initver="Redhat"
		elif grep -i centos /etc/*-release >/dev/null 2>&1 ; then
			distro="CentOS"
			initver="Redhat"
		elif grep -i red.hat.enterprise /etc/*-release >/dev/null 2>&1 ; then
			distro="RHEL"
			initver="Redhat"
		elif grep -i fedora /etc/*-release >/dev/null 2>&1 ; then
			distro="Fedora"
			initver="Redhat"
		elif [ -e /etc/redhat-release ]; then
			distro="Redhat"
			initver="Redhat"
		elif [ -e /etc/debian_version ]; then
			distro="Debian"
			initver="Debian"
		else
			abort "Could not determine Linux distribution."
		fi
		;;
	freebsd)
		initdir="/etc/rc.d"
		distro="FreeBSD"
		initver="FreeBSD"
		;;
	*)
		msg "Sorry, this install script doesn't support the '${platform}' platform."
		msg "Please contact VividCortex for installation support."
		abort ""
		;;
esac

if [ "${platform}" = "freebsd" ] ; then
	echo -n "Please enter the port your MySQL server is listening on: "

	if ! read MYSQLPORT; then
		echo
		abort "Unable to read MySQL port."
	fi

	if [ -z "$MYSQLPORT" ]; then
		abort "A MySQL port has to be provided."
	fi

	echo
fi

arch=$(getconf LONG_BIT 2>/dev/null)
[ -z "$arch" ] && arch=$(file /bin/sh | sed 's/.*[^[:digit:]]\([[:digit:]]*\)-bit.*/\1/')

case "$arch" in
	64)
		arch="amd64"
		;;
	32)
		arch="386"
		;;
	*)
		msg "Sorry, this install script doesn't support the '${arch}' architecture."
		msg "Please contact VividCortex for installation support."
		abort ""
esac

msg "Installing the VividCortex vc-agent-007 agent for ${platform} ${distro} ${arch}."

if [ -e "$globalconf" ]; then
	msg "$globalconf exists; stopping."
	msg "Remove and re-run if you wish to replace an existing install."
	abort ""
fi

# Download to temp folder in case we need to abort
tempdir=$(mktemp -d /tmp/vividcortex.XXXX)

if [ $? -ne 0 ]; then
	abort "Unable to create temp folder under /tmp"
fi

getfile "$baseuri/$platform/$arch/current/vc-agent-007" "$tempdir/vc-agent-007"
getfile "$baseuri/$platform/init-scripts/$initver/current/vividcortex" "$tempdir/vividcortex"
mv $tempdir/vc-agent-007 /usr/local/bin || abort "Unable to install vc-agent-007"
mv $tempdir/vividcortex $initdir/vividcortex || abort "Unable to install vividcortex init script"
chmod 700 /usr/local/bin/vc-agent-007 || abort "Unable to set /usr/local/bin/vc-agent-007 permissions"
chmod 755 $initdir/vividcortex || abort "Unable to set $initdir/vividcortex permissions"

rm -Rf $tempdir 2> /dev/null
tempdir=""

createdir "$confdir"
createdir "$logdir"

proxy=""
resp=""
echo -n "Do you need to set up an HTTP proxy? [y/N] "
if read resp && [ "$resp" = 'Y' -o "$resp" = 'y' ]; then
	proxy=${http_proxy:-''}
	echo -n "Please input your proxy URL [$proxy] "
	read proxy

	if [ -z "$proxy" ]; then
		proxy=${http_proxy:-''}
	fi

	if ! echo $proxy | grep "^https\?://" &> /dev/null; then
		proxy="http://$proxy"
	fi
fi
echo

if [ "${platform}" = "freebsd" ] ; then
	cat - > "$globalconf" <<EOF
{
    "api-token": "$VCTOKEN",
    "proxy-uri": "$proxy",
    "binding": "0:$MYSQLPORT"
}
EOF
else
	cat - > "$globalconf" <<EOF
{
    "api-token": "$VCTOKEN",
    "proxy-uri": "$proxy"
}
EOF
fi

chmod 600 "$globalconf"

[ $? -eq 0 ] || abort "Unable to create $globalconf"

echo "VividCortex agents successfully installed"
echo

resp=""
echo -n "Would you like to schedule automatic service startup? [Y/n] "

if read resp && [ "$resp" = 'Y' -o "$resp" = 'y' ]; then
	echo

	case "${initver}" in
		Redhat)
			/sbin/chkconfig --add vividcortex || abort "Unable to install init script"
			echo "VividCortex init script scheduled for automatic start/stop"
			;;
		Debian)
			update-rc.d vividcortex defaults || abort "Unable to install init script"
			echo "VividCortex init script scheduled for automatic start/stop"
			;;
		FreeBSD)
			# FIXME: As written, the FreeBSD script will *always* start the service.
			echo "VividCortex init script scheduled for automatic start/stop"
			;;
		*)
			msg "Sorry, don't know how to enable init scripts for '${initver}'."
			msg "Please enable the 'vividcortex' init script manually."
			msg "Please also tell VividCortex how to improve this script to do that."
			abort ""
			;;
	esac

	echo
fi

resp=""
echo -n "Would you like to start the service now? [Y/n] "

if read resp && [ -z "$resp" -o "$resp" = 'Y' -o "$resp" = 'y' ]; then
	echo "Starting VividCortex service"
	$initdir/vividcortex start
fi

echo
echo "Installation is done"
echo
exit 0

