#!/bin/sh

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

# This is a placeholder that is populated with the version of agents
# that the script is deployed with. It is here for information purposes only - DO NOT USE
VERSION=1.6.1

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


msg()
{
	if [ $# -gt 0 ]; then
		echo "$1" >&2
	else
		echo >&2
	fi
}

abort()
{
	if [ $# -gt 0 ]; then
		msg "$1"
	fi
	[ -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

# Note that I am using the external getopt(1) here rather than the bash-
# internal getopts() becauase /bin/sh on some operating systems (e.g. FreeBSD)
# is not bash.
GETARGS=$(getopt -o "hsp:t:v:" -l "help,autostart,no-autostart,start-now,no-proxy,proxy:,token:,version:" -n "$0" -- "$@")

if [ $? -ne 0 ]; then
	msg "Usage: install [-h|--help] [--autostart|--no-autostart] [-s|--start-now]"
	msg "               [--no-proxy] [-p|--proxy HTTP-proxy] [-t|--token API-token] [-v|--version version-number]"
	abort
fi

eval set -- "$GETARGS"

AUTOSTART=""
NOPROXY=""
PROXY=""
STARTNOW=""
VCTOKEN=""
INSTALL_VERSION=current

while true; do
	case "$1" in
		--autostart)
			shift
			AUTOSTART=1
			;;
		--no-autostart)
			shift
			AUTOSTART=0
			;;
		-s|--start-now)
			shift
			STARTNOW=1
			;;
		--no-proxy)
			shift
			NOPROXY=1
			PROXY=""
			;;
		-p|--proxy)
			shift
			if [ -n "$1" ]; then
				PROXY="$1"
				NOPROXY=""
				shift
			fi
			# Undocumented, but worth honoring anyway just to be neighborly.
			if [ "$PROXY" = "no" -o "$PROXY" = "none" -o "$PROXY" = "false" -o "$PROXY" = "off" ]; then
				PROXY=""
				NOPROXY=1
			fi
			;;
		-t|--token)
			shift
			if [ -n "$1" ]; then
				VCTOKEN="$1"
				shift
			fi
			;;
		-v|--version)
			shift
			if [ -n "$1" ]; then
				INSTALL_VERSION="$1"
				shift
			fi
			;;
		-h|--help)
			shift
			echo
			echo "Usage: install [-h|--help] [--autostart|--no-autostart] [-s|--start-now]"
			echo "               [--no-proxy] [-p|--proxy HTTP-proxy] [-t|--token API-token] [-v|--version version-number]"
			echo
			echo "Where:"
			echo
			echo "--help [-h]                Display this help information"
			echo "--autostart                Configure system to start VividCortex at boot"
			echo "--no-autostart             Do not configure system to start VividCortex at boot"
			echo "--start-now [-s]           Start VividCortex services after installation"
			echo "--no-proxy                 Do not configure an HTTP proxy"
			echo "--proxy [-p] 'HTTP-proxy'  Configure HTTP proxy to 'HTTP-proxy'"
			echo "--token [-t] 'API-token'   Configure VividCortex token to 'API-token'"
			echo "--version [-t] 'Version		Install the specified version of VividCortex (installs latest if not specified)"
			echo
			echo "For some configuration parameters, if no option is specified, 'install' will"
			echo "fall back to interactive querying to obtain the parameters."
			echo
			exit 0
			;;
		--)
			shift
			break
			;;
	esac
done

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

if [ -z "${VCTOKEN}" ]; then
	echo -n "Please enter your VividCortex API token: "

	if ! read VCTOKEN; then
		echo
		abort "Unable to read API token."
	fi
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

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

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

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

if [ -n "${NOPROXY}" ]; then
	proxy=""
elif [ -n "${PROXY}" ]; then
	proxy="${PROXY}"
else
	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
fi

export http_proxy=$proxy
export https_proxy=$proxy

# 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

if [ $INSTALL_VERSION != "current" ]; then
	echo "Installing VividCortex version: " $INSTALL_VERSION
fi

getfile "$baseuri/$platform/$arch/$INSTALL_VERSION/vc-agent-007" "$tempdir/vc-agent-007"
getfile "$baseuri/$platform/init-scripts/$initver/$INSTALL_VERSION/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"

cat - > "$globalconf" <<EOF
{
    "api-token": "$VCTOKEN",
    "proxy-uri": "$proxy"
}
EOF

chmod 600 "$globalconf"

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

echo "VividCortex agents successfully installed"
echo

resp=""
if [ -z "$AUTOSTART" ]; then
	echo -n "Would you like to schedule automatic service startup? [Y/n] "
	read resp
	echo
fi

if [ "$resp" = 'Y' -o "$resp" = 'y' -o "$AUTOSTART" = "1" ]; then
	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--
			# even if --no-autostart was specified.
			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
else
	echo "VividCortex init script *NOT* scheduled for automatic start/stop"
fi

echo

if [ "$STARTNOW" = 1 ]; then
	echo "Starting VividCortex service"
	echo
	$initdir/vividcortex start

	if [ $? -ne 0 ]; then
		msg
		msg "VividCortex service startup may have failed."
		msg "Please inspect '$logdir/vc-agent-007.log' for details."
		msg
		msg "VividCortex service can be started by running:"
		msg
		msg "    $initdir/vividcortex start"
	fi
else
	echo "VividCortex service can be started by running:"
	echo
	echo "    $initdir/vividcortex start"
fi

echo
echo "Installation is done"
echo
exit 0
