#!/bin/sh

# This program is Copyright (c) 2013-2015 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.763

# Placeholder that is populated with the base URI for the download server - DO NOT USE
baseuri=https://download.vividcortex.com

set -u
POSIXLY_CORRECT=1
export POSIXLY_CORRECT

confdir=/etc/vividcortex
globalconf="${confdir}/global.conf"
logdir=/var/log/vividcortex
tempdir=""
socks5=""
SKIPCERTS=""
LOADCERTS=""

EXISTS="command -v"
${EXISTS} ls >/dev/null 2>&1 || EXISTS=which
if ! ${EXISTS} ls >/dev/null 2>&1 ; then
	echo "command/which failed"
	exit 1
fi

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

abort()
{
	if [ $# -gt 0 ]; then
		msg
		msg "$1"
		msg
	fi
	[ -n "${tempdir}" ] && rm -Rf "${tempdir}" >/dev/null 2>&1
	exit 1
}

# Deprecated: override baseuri when ${VC_CUSTOM_URI} var is set
test -n "${VC_CUSTOM_URI:-}" && abort "VC_CUSTOM_URI deprecated, use --api-uri and --cdn-uri"

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

getfile()
{
	failed=0
	if ${EXISTS} curl >/dev/null 2>&1 ; then
		if [ -z "${socks5}" ]; then
			curl -f -s "$1" > "$2" && return 0
			test -n "${SKIPCERTS}" && curl -k -f -s "$1" > "$2" && return 0
		else
			curl -f -s --socks5-hostname "${socks5}" "$1" > "$2" && return 0
			curl -f -s --socks5 "${socks5}" "$1" > "$2" && return 0
			curl -f -s -x "socks5://${socks5}" "$1" > "$2" && return 0
			test -n "${SKIPCERTS}" && curl -k -f -s --socks5-hostname "${socks5}" "$1" > "$2" && return 0
			test -n "${SKIPCERTS}" && curl -k -f -s --socks5 "${socks5}" "$1" > "$2" && return 0
			test -n "${SKIPCERTS}" && curl -k -f -s -x "socks5://${socks5}" "$1" > "$2" && return 0
		fi
		failed=1
	fi
	if ${EXISTS} wget >/dev/null 2>&1 ; then
		# depending on version, uses env vars
		wget -q -O - "$1" > "$2" && return 0
		test -n "${SKIPCERTS}" && wget --no-check-certificate -q -O - "$1" > "$2" && return 0
		failed=1
	fi
	if ${EXISTS} fetch >/dev/null 2>&1 ; then
		# fetch uses env vars and does not support socks5
		fetch -q -o - "$1" > "$2" && return 0
		test -n "${SKIPCERTS}" && fetch --no-verify-peer -q -o - "$1" > "$2" && return 0
		failed=1
	fi

	if [ $failed -eq 0 ]; then
		abort "No suitable tool for file download found"
	fi

	dlHelp="Unable to retrieve $1

Please verify proxy/firewall and install or update CA Root Certificates"

	case "${initver}" in
		FreeBSD)
			abort "${dlHelp} - e.g. pkg install security/ca_root_nss"
			;;
		Redhat)
			if [ "${distro}" = "Slackware" ]; then
				abort "${dlHelp} - e.g. update-ca-certificates"
			else
				abort "${dlHelp} - e.g. yum update ca-certificates"
			fi
			;;
		Debian|OpenRC|systemd)
			if [ "${distro}" = "SuSE" ]; then
				abort "${dlHelp} - e.g. zypper install ca-certificates ; update-ca-certificates"
			else
				abort "${dlHelp} - e.g. update-ca-certificates"
			fi
			;;
		*)
			abort "${dlHelp}."
			;;
	esac
}

usage()
{
	abort "Usage: install [-h|--help] [--autostart|--no-autostart] [-s|--start-now]
          [-t|--token API-token] [--no-proxy] [-p|--proxy URI] [-i|--init INIT]
          [-a|--api-uri URI] [-c|--cdn-uri URI] [-v|--version TAG]

Where:

  --help [-h]           Display this help information
  --autostart           Configure system to start VividCortex at boot
  --no-autostart        Do not configure system to start VividCortex at boot
  --start-now [-s]      Start VividCortex services after installation
  --token [-t] 'TOKEN'  Configure VividCortex token to 'TOKEN'
  --no-proxy            Do not configure an HTTP proxy
  --proxy [-p] 'URI/auto/dyn' Configure HTTP/HTTPS or SOCKS5 proxy to 'URI',
      'auto' sets whatever proxy (or no proxy) is detected in environment vars,
      and 'dyn' makes VividCortex agents detect proxies every time they start.
  --init [-i] 'INIT'    Linux only. Override init detection and use the
                        specified init setup [Debian, OpenRC, Redhat].
  --api-uri [-a] 'URI'  Use custom API endpoint 'URI'
  --cdn-uri [-c] 'URI'  Use custom CDN endpoint 'URI'
  --version [-v] 'TAG'  Install VividCortex version 'TAG' (latest otherwise)

For some configuration parameters, if no option is specified, 'install' will
fall back to interactive querying to obtain the parameters."
}

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

if ${EXISTS} hostname >/dev/null 2>&1 ; then # generic
	if [ "$(hostname)" = "" ]; then
		abort "VividCortex requires hostname to be set"
	fi
elif [ -f /proc/sys/kernel/hostname ]; then # Linux
	if [ "$(cat /proc/sys/kernel/hostname)" = "" ]; then
		abort "VividCortex requires hostname to be set.
Please contact VividCortex for installation support.
Additional information: proc / $(uname -a)"
	fi
elif ${EXISTS} sysctl >/dev/null 2>&1 ; then # BSD
	if [ "$(sysctl -b -q kern.hostname)" = "" ]; then
		abort "VividCortex requires hostname to be set.
Please contact VividCortex for installation support.
Additional information: sysctl / $(uname -a)"
	fi
else
	abort "VividCortex requires hostname to be set.
Please contact VividCortex for installation support.
Additional information: else / $(uname -a)"
fi

test -d /usr || abort "/usr not mounted"

# Note that I am using the external getopt(1) here rather than the bash-
# internal getopts() because /bin/sh on some operating systems (e.g. FreeBSD)
# is not bash.
(getopt -T) >/dev/null 2>&1
exitcode=$?
if [ ${exitcode} -eq 4 ]; then
	# GNU version, supports long options
	GETARGS=$(getopt -o "hslkp:t:v:i:a:c:" -l "help,autostart,no-autostart,start-now,load-certs,skip-certs,no-proxy,proxy:,token:,version:,init:,api-uri:,cdn-uri:" -n "$0" -- "$@") 2>/dev/null
	test $? -eq 0 || usage
	eval set -- "${GETARGS}"
else
	# BSD, cannot validate
	eval set -- "$*"
fi

AUTOSTART=""
NOPROXY=""
PROXY=""
STARTNOW=""
VCTOKEN=""
APIURI=""
CDNURI=""
API_TRANSPORT="HTTPS"
API_PORT="443"
FORCE_INIT=""
INSTALL_VERSION=current

if [ -n "${SSL_NO_VERIFY_PEER:-}" ]; then
	SKIPCERTS=1
	LOADCERTS=1
fi

while [ $# -ne 0 ] ; do
	case "$1" in
		--autostart)
			shift
			AUTOSTART=1
			;;
		--no-autostart)
			shift
			AUTOSTART=0
			;;
		-s|--start-now)
			shift
			STARTNOW=1
			;;
		-l|--load-certs)
			shift
			LOADCERTS=1
			;;
		-k|--skip-certs)
			shift
			SKIPCERTS=1
			LOADCERTS=1
			;;
		--no-proxy)
			shift
			NOPROXY=1
			PROXY=""
			;;
		-p|--proxy)
			shift
			if [ -n "$1" ]; then
				NOPROXY=""
				PROXY="$1"
				shift
				# Undocumented, but worth honoring anyway just to be neighborly.
				if [ "${PROXY}" = "no" ] || [ "${PROXY}" = "none" ] || [ "${PROXY}" = "false" ] || [ "${PROXY}" = "off" ]; then
					NOPROXY=1
					PROXY=""
				fi
			fi
			;;
		-i|--init)
			shift
			FORCE_INIT="$1"
			if [ "${FORCE_INIT}" != "Debian" ] && [ "${FORCE_INIT}" != "OpenRC" ] && [ "${FORCE_INIT}" != "Redhat" ]; then
				abort "init must be Debian, OpenRC or Redhat"
			fi
			shift
			;;
		-a|--api-uri)
			shift
			test -z "$1" && abort "--api-uri requires a value"
			APIURI="$1"
			echo "${APIURI}" | grep '^http' >/dev/null 2>&1 || abort "--api-uri must be http or https"
			if ! echo "${APIURI}" | grep '^https' >/dev/null 2>&1 ; then
				API_TRANSPORT="HTTP"
				API_PORT="80"
			fi
			shift
			;;
		-c|--cdn-uri)
			shift
			test -z "$1" && abort "--cdn-uri requires a value"
			CDNURI="$1"
			baseuri="$1"
			echo "${CDNURI}" | grep '^http' >/dev/null 2>&1 || abort "--cdn-uri must be http or https"
			shift
			;;
		-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
			usage
			;;
		--)
			shift
			break
			;;
		*)
			shift
			usage
			;;
	esac
done

platform=$(uname -s | tr A-Z a-z)
distro=""
arch=""
initver=""
initdir=""
initname="vividcortex"
initperm=755
startcmd=""
stopcmd=""
installcmd=""
uninstallcmd="true"
defaultvcbindir="/usr/local/bin"
vcbindir="${defaultvcbindir}"

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

case "${longbit}" in
	64)
		arch="amd64"
		;;
	32)
		abort "VividCortex isn't supported on 32-bit systems"
		;;
	*)
		abort "Could not determine system configuration.
Please contact VividCortex for installation support.
Additional information: $(uname -a)"
		;;
esac

# aborts or sets (distro) or (distro,initdir,initver)
case "${platform}" in
	linux)
		initdir="/etc/init.d"

		if [ -n "${FORCE_INIT}" ]; then
			initver="${FORCE_INIT}"
			test -d "${initdir}" || initdir="/etc/rc.d"
			test -d "${initdir}" || abort "Cannot find directory for init scripts"
			distro="Unknown-${FORCE_INIT}"
		elif 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 grep 'ID=coreos' /etc/os-release >/dev/null 2>&1 ; then
			distro="CoreOS"
			#systemd
		elif grep 'ID=alpine' /etc/os-release >/dev/null 2>&1 ; then
			distro="Alpine"
			initver="OpenRC"
		elif grep 'ID=slackware' /etc/os-release >/dev/null 2>&1 ; then
			distro="Slackware"
			initdir="/etc/rc.d"
			initver="Redhat"
		elif grep 'ID=arch' /etc/os-release >/dev/null 2>&1 ; then
			distro="Arch"
			#systemd
		elif [ -e /etc/redhat-release ]; then
			distro="Redhat"
			initver="Redhat"
		elif [ -e /etc/debian_version ]; then
			distro="Debian"
			initver="Debian"
		elif [ -e /etc/gentoo-release ]; then
			distro="Gentoo"
			initver="OpenRC"
		elif [ -e /etc/SuSE-release ]; then
			distro="SuSE"
			initver="Debian"
		else
			distro="Unknown"
			# don't abort, it may be an unknown systemd-based distro
		fi
		;;
	freebsd)
		initdir="/etc/rc.d"
		distro="FreeBSD"
		initver="FreeBSD"
		;;
	XXXdarwinXXX)
		# to-do: remove XXX if/when we build binaries for Darwin
		distro="Darwin"
		initver="launchd"
		initdir="/Library/LaunchDaemons"
		initname="com.vividcortex.supervisor.plist"
		;;
	*)
		abort "Sorry, this install script doesn't support the '${platform}' platform.
Please contact VividCortex for installation support.
Additional information: $(uname -a)"
		;;
esac

# linux: do we need to use systemd instead of legacy initver?
if [ "${platform}" = "linux" ] && [ "${FORCE_INIT}" = "" ]; then
	if [ -d /etc/systemd/system ]; then
		if ${EXISTS} systemctl >/dev/null 2>&1 ; then
			# installed; enabled?
			export SYSTEMD_PAGER=
			if systemctl >/dev/null 2>&1 ; then
				# enabled; in use?
				if systemctl | grep -q "\.service" ; then
					initver="systemd"
					test "${distro}" = "CoreOS" && vcbindir="/vividcortex"
				fi
			fi
		fi
	fi
fi

# verify initver dependencies and set startcmd/stopcmd/installcmd
case "${initver}" in
	Redhat)
		startcmd="${initdir}/vividcortex start"
		stopcmd="${initdir}/vividcortex stop"
		if [ "${distro}" = "Slackware" ]; then
			installcmd="ln -s -f ${initdir}/vividcortex /etc/rc.d/rc3.d/Svividcortex"
			uninstallcmd="rm -f /etc/rc.d/rc?.d/?vividcortex && rm -f ${initdir}/vividcortex"
		else
			installcmd="/sbin/chkconfig --add vividcortex"
			uninstallcmd="/sbin/chkconfig --del vividcortex"
			${EXISTS} /sbin/chkconfig >/dev/null 2>&1 || initver=""
		fi
		;;
	Debian)
		if ${EXISTS} update-rc.d >/dev/null 2>&1 ; then
			startcmd="${initdir}/vividcortex start"
			stopcmd="${initdir}/vividcortex stop"
			installcmd="update-rc.d vividcortex defaults"
		elif ${EXISTS} /sbin/chkconfig >/dev/null 2>&1 ; then
			startcmd="${initdir}/vividcortex start"
			stopcmd="${initdir}/vividcortex stop"
			installcmd="/sbin/chkconfig --add vividcortex"
			uninstallcmd="/sbin/chkconfig --del vividcortex"
		else
			initver=""
		fi
		;;
	OpenRC)
		startcmd="rc-service vividcortex start"
		stopcmd="rc-service vividcortex stop"
		installcmd="rc-update add vividcortex"
		${EXISTS} rc-update >/dev/null 2>&1 || initver=""
		${EXISTS} rc-service >/dev/null 2>&1 || initver=""
		;;
	systemd)
		startcmd="systemctl start vividcortex.service"
		stopcmd="systemctl stop vividcortex.service"
		installcmd="systemd_install"
		initdir="/etc/systemd/system"
		initname="vividcortex.service"
		initperm=644
		;;
	launchd)
		startcmd="launchctl start com.vividcortex.supervisor"
		stopcmd="launchctl stop com.vividcortex.supervisor"
		installcmd="launchctl load -w ${initdir}/${initname}"
		uninstallcmd="launchctl unload -w ${initdir}/${initname}"
		${EXISTS} launchctl >/dev/null 2>&1 || initver=""
		# to-do
		if [ "${AUTOSTART}" = "0" ]; then
			abort "Not-autostarting unsupported"
		fi
		AUTOSTART="1"
		;;
	FreeBSD)
		startcmd="${initdir}/vividcortex start"
		stopcmd="${initdir}/vividcortex stop"
		installcmd="true"
		if [ "${AUTOSTART}" = "0" ]; then
			abort "Not-autostarting unsupported"
		fi
		AUTOSTART="1"
		;;
	*)
		initver=""
		;;
esac

systemd_install () {
	systemctl daemon-reload
	systemctl enable vividcortex.service
}


if [ "${initver}" = "" ] || [ "${initdir}" = "" ] || [ ! -d "${initdir}" ]; then
	abort "Sorry, install does not yet support your version or flavor of ${platform}/${distro}.

Additional information: $(uname -a)

Please contact VividCortex for installation support."
fi


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

# agents are installed in ${vcbindir}; make sure it exists
if [ ! -d "${vcbindir}" ]; then
	if [ "${vcbindir}" = "/usr/local/bin" ] && [ ! -d /usr/local ]; then
		mkdir /usr/local >/dev/null 2>&1
		chmod 755 /usr/local >/dev/null 2>&1
	fi
	mkdir "${vcbindir}" >/dev/null 2>&1
	chmod 755 "${vcbindir}" >/dev/null 2>&1
	test -d "${vcbindir}" || abort "Cannot create ${vcbindir}"
fi

# customer consented a reinstall by removing globalconf; make sure service isn't running
if [ -e "${initdir}/${initname}" ]; then
	${stopcmd} >/dev/null 2>&1
	${uninstallcmd} >/dev/null 2>&1
	rm -f /var/lock/subsys/vividcortex >/dev/null 2>&1
fi

# remove service file
rm -f "${initdir}/${initname}"

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

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

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

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

# detect proxy
detProxy=${HTTPS_PROXY:-''}
test -n "${detProxy}" && echo "${detProxy}" | grep -v '://' >/dev/null 2>&1 && detProxy="https://${detProxy}"
echo "${detProxy}" | grep '^http' >/dev/null 2>&1 || detProxy=${https_proxy:-''}
test -n "${detProxy}" && echo "${detProxy}" | grep -v '://' >/dev/null 2>&1 && detProxy="https://${detProxy}"
echo "${detProxy}" | grep '^http' >/dev/null 2>&1 || detProxy=${HTTP_PROXY:-''}
test -n "${detProxy}" && echo "${detProxy}" | grep -v '://' >/dev/null 2>&1 && detProxy="http://${detProxy}"
echo "${detProxy}" | grep '^http' >/dev/null 2>&1 || detProxy=${http_proxy:-''}
test -n "${detProxy}" && echo "${detProxy}" | grep -v '://' >/dev/null 2>&1 && detProxy="http://${detProxy}"
echo "${detProxy}" | grep '^http' >/dev/null 2>&1 || detProxy=${SOCKS_SERVER:-''}
test -n "${detProxy}" && echo "${detProxy}" | grep -v '://' >/dev/null 2>&1 && detProxy="socks5://${detProxy}"
echo "${detProxy}" | grep '^http\|^socks' >/dev/null 2>&1 || detProxy=${ALL_PROXY:-''}
test -n "${detProxy}" && echo "${detProxy}" | grep -v '://' >/dev/null 2>&1 && detProxy="socks5://${detProxy}"
echo "${detProxy}" | grep '^http\|^socks' >/dev/null 2>&1 || detProxy=${all_proxy:-''}
test -n "${detProxy}" && echo "${detProxy}" | grep -v '://' >/dev/null 2>&1 && detProxy="socks5://${detProxy}"
echo "${detProxy}" | grep '^http\|^socks' >/dev/null 2>&1 || detProxy=""

proxy=""
dynmsg=""

if [ -n "${NOPROXY}" ]; then
	test -n "${detProxy}" && dynmsg=" because of --no-proxy. If install fails, consider removing
that option as ${detProxy} may be a valid proxy."
elif [ "${PROXY}" = "auto" ]; then
	proxy="${detProxy}"
	dynmsg="  (auto-detected)"
elif [ "${PROXY}" = "dyn" ]; then
	proxy="${detProxy}"
	dynmsg="  (will re-detect every time an agent starts)"
elif [ -n "${PROXY}" ]; then
	proxy="${PROXY}"
else
	resp=""
	echo
	echo -n "Do you need to set up a proxy? [y/N] "
	if read -r resp && [ "${resp}" = 'Y' ] || [ "${resp}" = 'y' ]; then
		if [ -n "${detProxy}" ]; then
			echo
			echo "Environment vars suggest this may be a valid proxy: ${detProxy}"
		fi
		echo
		echo -n "Please input your proxy URI: "
		read -r proxy
		test -z "${proxy}" && abort "Blank proxy; retry install"
	fi
fi

unset ALL_PROXY all_proxy HTTP_PROXY http_proxy HTTP_PROXY_AUTH HTTPS_PROXY https_proxy SOCKS_SERVER SOCKS_VERSION SSL_NO_VERIFY_PEER
if [ -n "${proxy}" ]; then
	if echo "${proxy}" | grep "^\(socks5\|socks\)://" >/dev/null 2>&1 ; then
		# socks5 proxy
		socks5=$(echo "${proxy}" | sed 's/[^:]\+:\/\///')
		export SOCKS_SERVER="${socks5}"
		export SOCKS_VERSION=5
		export ALL_PROXY="${proxy}"
		export all_proxy="${proxy}"
	elif echo "${proxy}" | grep "^\(https\|http\)://" >/dev/null 2>&1 ; then
		# https/http proxy
		export HTTP_PROXY="${proxy}"
		export http_proxy="${proxy}"
		export HTTPS_PROXY="${proxy}"
		export https_proxy="${proxy}"
	else
		abort "Unsupported proxy URI: ${proxy}
Proxy URI must begin with 'https://', 'http://', 'socks5://' or 'socks://'.
E.g.: socks5://user:pass@127.0.0.1:1080"
	fi
	echo
	echo "Using proxy: ${proxy}${dynmsg}"
else
	# try harder to not use a proxy
	export NO_PROXY="$(echo "${baseuri}" | sed 's/.*:\/\///' | sed 's/\/.*$//')"
	export no_proxy="${NO_PROXY}"
	echo
	echo "Not using a proxy${dynmsg}"
fi
test "${PROXY}" = "dyn" && proxy="auto"

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

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

if [ "${INSTALL_VERSION}" != "current" ]; then
	echo
	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 -f "${tempdir}/vc-agent-007" "${vcbindir}/" || abort "Unable to install vc-agent-007"
chmod 700 "${vcbindir}/vc-agent-007" || abort "Unable to set ${vcbindir}/vc-agent-007 permissions"

# Verify that env looks good to 007

EXTRA_ARG=""
API_DOMAIN="app.vividcortex.com"
if [ -n "${APIURI}" ]; then
	EXTRA_ARG="-api-uri=${APIURI}"
	API_DOMAIN=$(echo "${APIURI}" | sed -e 's|^[^/]*//||' -e 's|/.*$||')
fi
if [ "${vcbindir}" != "${defaultvcbindir}" ]; then
	test -n "${EXTRA_ARG}" && EXTRA_ARG="${EXTRA_ARG} "
	EXTRA_ARG="${EXTRA_ARG}-agent-install-dir=${vcbindir}/"
fi
if [ -n "${LOADCERTS}" ]; then
	test -n "${EXTRA_ARG}" && EXTRA_ARG="${EXTRA_ARG} "
	EXTRA_ARG="${EXTRA_ARG}-override-os-certs"
fi
{ "${vcbindir}/vc-agent-007" -self-test -proxy-uri="${proxy}" -config-file="" -api-token="${VCTOKEN}" ${EXTRA_ARG} ; } >"${tempdir}/vc-agent-007.log" 2>&1
exitcode=$?
# 0 exitSuccess, 2 exitBadOptions (pre-1.6.143 vc-agent-007 doesn't support -self-test)
if [ ${exitcode} -ne 0 ]; then
	rm -f "${vcbindir}/vc-agent-007"
	if   [ ${exitcode} -eq 3 ]; then  # exitNoToken
		abort "The API token you used, ${VCTOKEN}, is not valid, please verify and retry installation"
	elif [ ${exitcode} -eq 4 ]; then  # exitBadProxy
		abort "Cannot use proxy [ ${proxy} ], please verify and retry installation"
	elif [ ${exitcode} -eq 7 ]; then  # exitCantReachAPI
		if [ "${platform}" = "freebsd" ] && [ ! -f /usr/local/share/certs/ca-root-nss.crt ]; then
			abort "Cannot reach VividCortex. Please verify that proxy/firewall allows outgoing
${API_TRANSPORT} (port ${API_PORT}) to [${API_DOMAIN}], CA root certificates present (pkg install security/ca_root_nss), and retry installation."
		elif [ "${distro}" = "SuSE" ]; then
			abort "Cannot reach VividCortex. Please verify that proxy/firewall allows outgoing
${API_TRANSPORT} (port ${API_PORT}) to [${API_DOMAIN}], and retry installation.

You may need to install or update CA Root Certificates - e.g. zypper install ca-certificates ; update-ca-certificates"
		else
			abort "Cannot reach VividCortex. Please verify that proxy/firewall allows outgoing
${API_TRANSPORT} (port ${API_PORT}) to [${API_DOMAIN}], and retry installation."
		fi
	elif [ ${exitcode} -eq 8 ]; then # exitUnsupported
		abort "OS version probably unsupported, please contact VividCortex.

Self-test log:
$(cat "${tempdir}/vc-agent-007.log")

Additional information: ${distro}/${arch} (exitcode=${exitcode}) $(uname -a)"
	elif [ ${exitcode} -eq 9 ]; then # exitNoAdmin
		abort "Process is unable to secure root privileges, please contact VividCortex.

Self-test log:
$(cat "${tempdir}/vc-agent-007.log")

Additional information: ${distro}/${arch} (exitcode=${exitcode}) $(uname -a)"
	elif [ ${exitcode} -ge 125 ]; then # 125 panic, 126 access denied, 127 not a valid program, 128+signal
		abort "OS version probably unsupported, please contact VividCortex.

Self-test log:
$(cat "${tempdir}/vc-agent-007.log")

Additional information: ${distro}/${arch} (exitcode=${exitcode}) $(uname -a)"
	else
		abort "Installation failed. Please retry and, if the problem persists, contact VividCortex.

Self-test log:
$(cat "${tempdir}/vc-agent-007.log")

Additional information: ${distro}/${arch} (exitcode=${exitcode}) $(uname -a)"
	fi
fi

if [ "${vcbindir}" != "${defaultvcbindir}" ]; then
	escFrom=$(echo "${defaultvcbindir}" | sed 's/\//\\\&/g')
	escTo=$(echo "${vcbindir}" | sed 's/\//\\\&/g')
	sed -i "s/${escFrom}/${escTo}/g" "${tempdir}/vividcortex" >/dev/null 2>&1 || abort "Failed to replace vcbindir in init script"
fi

mv -f "${tempdir}/vividcortex" "${initdir}/${initname}" || abort "Unable to install vividcortex init script"
chmod ${initperm} "${initdir}/${initname}" || abort "Unable to set ${initdir}/${initname} permissions"

rm -Rf "${tempdir}" >/dev/null 2>&1
tempdir=""

createdir "${confdir}"
createdir "${logdir}"

rm -f "${globalconf}.tmp"

cat - > "${globalconf}.tmp" <<EOF
{

EOF

if [ -n "${APIURI}" ]; then
	cat - >> "${globalconf}.tmp" <<EOF
    "api-uri": "${APIURI}",
EOF
fi

if [ -n "${CDNURI}" ]; then
	cat - >> "${globalconf}.tmp" <<EOF
    "cdn-uri": "${CDNURI}",
EOF
fi

if [ "${vcbindir}" != "${defaultvcbindir}" ]; then
	cat - >> "${globalconf}.tmp" <<EOF
    "agent-install-dir": "${vcbindir}/",
EOF
fi

if [ -n "${LOADCERTS}" ]; then
	cat - >> "${globalconf}.tmp" <<EOF
    "override-os-certs": "true",
EOF
fi

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

mv -f "${globalconf}.tmp" "${globalconf}"

chmod 600 "${globalconf}" || abort "Unable to create ${globalconf}"

echo
echo "VividCortex agents successfully installed"
echo

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

if [ "${resp}" = 'Y' ] || [ "${resp}" = 'y' ] || [ "${AUTOSTART}" = "1" ]; then
	if [ "${installcmd}" = "" ]; then
		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 ""
	else
		${installcmd} >/dev/null 2>&1 || abort "Unable to install init script using '${installcmd}'"
	fi
	echo "VividCortex init script scheduled for automatic start/stop"
else
	echo "VividCortex init script *NOT* scheduled for automatic start/stop"
fi

echo

if [ "${STARTNOW}" = 1 ]; then
	echo "Starting VividCortex service"
	${startcmd} >/dev/null 2>&1

	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 "    ${startcmd}"
	fi
else
	echo "VividCortex service can be started by running:"
	echo
	echo "    ${startcmd}"
fi

echo
echo "Installation is done; please check the VividCortex app to see the new host"
echo
exit 0
