#!/usr/bin/env bash

# Installs Banyan Netagent as an upstart or systemd service.
DIR=$( cd "$( dirname "$0" )" && pwd )

DIRBIN=${DIR}/x/bin
DIRETC=${DIR}/x/etc
DIRKMS=${DIR}/x/kms

config_file=${DIR}/config.yaml
log_home=/var/log/banyan

#!/bin/bash
banner () {
  echo "!!! You are on a Netagent 2.y.z release."
  echo "!!! Before continuing, make sure to consult the Banyan documentation as configuration of the Netagent has changed."
  echo "!!! See: https://docs.banyansecurity.io/docs/banyan-components/accesstier/install/tarball"
  read -p "Press ENTER to acknowledge and continue: "
  echo -e 
}

# Remove any double quotes with this version of yaml_value
yaml_value () {
	value=$(awk "/$1/"'{n=split($0,a,":"); if (n<=2) {print a[n]} else {joined=a[2]; for (i=3; i<=n; i++) {joined = joined ":" a[i]}; print joined}}' $2 | sed -e 's/"//g' | sed -e "s/'//g")
}

prompt_yn_question () {
  result=false
  while true; do
    read -p "$1 [Yn] " yn
    case $yn in
      [Yy]* ) result=1; break;;
      [Nn]* ) result=0; break;;
      * ) echo "Please answer yes (Yy) or no (Nn).";;
    esac
  done
}

# Start running code from here
dest_file=/opt/banyan/config.yaml

API_KEY_SECRET=${API_KEY_SECRET:-}
COMMAND_CENTER_URL=${COMMAND_CENTER_URL:-}

if [[ "$EUID" -ne 0 ]]; then
  echo "Error: Please run this script as root or use sudo."
  exit 1
fi

# Figure out whether we should skip any prompting for this script
if [[ $# -eq 1 && "$1" == "noprompt" ]]; then
  noprompt=1
else
  noprompt=0
fi

# Check if destination file (config.yaml) already exists
if [[ -f ${dest_file} ]]; then
  dest_file_exists=1
else
  # If there's no destination file, always overwrite
  overwrite=1
  dest_file_exists=0
fi

if [[ $dest_file_exists -eq 1 ]]; then
  if [[ $noprompt -eq 0 ]]; then
    banner
  fi
fi

if [[ $dest_file_exists -eq 1 ]]; then
  if [[ $noprompt -eq 0 ]]; then
    prompt_yn_question "Do you wish to overwrite $dest_file with the installer's config.yaml?"
    overwrite=$result
  else
    overwrite=1
  fi
fi

# Install dependencies by default
INSTALL_DEPS=${INSTALL_DEPS:-true}

if [[ $# -gt 1 ]]; then
	echo "Usage: $0"
	exit 1
fi

if [[ $overwrite -eq 1 ]]; then
	if [[ ! -f ${config_file} ]]; then
		echo "Error: Missing config file ${config_file}"
		exit 1
	fi
fi

# Prepare to install dependencies
function install_deps_prepare {
  # try to locate yum, fall back to apt-get
  if [[ $(command -v yum) ]]; then
    sudo yum clean metadata
    check_error "sudo yum clean metadata"
  else
    sudo DEBIAN_FRONTEND=noninteractive apt-get -q=2 update
    check_error "sudo apt-get update"
  fi
}

# Install dependencies, exit on any error
function install_deps {
  local deps=("${@}")

  # try to locate yum, fall back to apt-get
  if [[ $(command -v yum) ]]; then
    sudo yum -y -q install "${deps[@]}"
    check_error "sudo yum install ${deps[*]}"
  else
    sudo DEBIAN_FRONTEND=noninteractive apt-get -q=2 -y install "${deps[@]}"
    check_error "sudo apt-get install ${deps[*]}"
    setup_cgroup
  fi
}

# Install dependencies, do NOT exit on error
function install_deps_without_exit {
  local deps=("${@}")

  if [[ $(command -v yum) ]]; then
    sudo yum -y -q install "${deps[@]}" 2> /dev/null
  else
    sudo DEBIAN_FRONTEND=noninteractive apt-get -q=2 -y install "${deps[@]}" 2> /dev/null
  fi
}

function check_error {
	local err=$?
	if [[ ${err} -ne 0 ]]; then
		echo "$1 Error: ${err}"
		exit 1
	fi
}

function setup_cgroup {
  # return if cpu cgroup subsystem mounted
	[[ -f /sys/fs/cgroup/cpu ]] && return

	# return if os-release is missing
	[[ -f /etc/os-release ]] || return

	# return if not 14.04
	grep -q 14.04 /etc/os-release || return

	# looks like ubuntu 14.04
	sudo DEBIAN_FRONTEND=noninteractive apt-get -q=2 -y install cgroup-lite
	check_error "apt-get install cgroup-lite"

	sudo cgroups-mount
}

if [[ $overwrite -eq 1 ]]; then
	# validate config values
	yaml_value "api_key_secret" $config_file
  api_key_secret=$value
	if [[ -z ${api_key_secret} ]]; then
		echo "Error: api_key_secret not defined in ${config_file}"
		exit 1
	fi
	yaml_value "command_center_url" $config_file
  command_center_url=$value
	if [[ -z ${command_center_url} ]]; then
		echo "Error: command_center_url not defined in ${config_file}"
		exit 1
	fi
	yaml_value "access_tier_name" $config_file
  access_tier_name=$value
	if [[ -z ${access_tier_name} ]]; then
		echo "Error: access_tier_name not defined in ${config_file}"
		exit 1
	fi
	echo "Using command center URL ${command_center_url} and access tier name ${access_tier_name}"
fi

sudo install -d -m 0755 /opt/banyan
check_error "install -d -m 0755 /opt/banyan"

sudo install -d -m 0755 ${log_home}
check_error "install -d -m 0755 ${log_home}"

echo "Logs will be stored in ${log_home}/netagent.log"

# install dependencies
if [[ ${INSTALL_DEPS} == "true" ]]; then
	install_deps_prepare
	install_deps ipset ebtables iptables jq
	grep -q -v Amazon /etc/os-release && install_deps_without_exit wireguard
fi

[[ -d /opt/banyan/local ]] && sudo rm -rf /opt/banyan/local

INIT_SYSTEM_CMD=(sudo $(command -v systemctl || command -v initctl))
"${INIT_SYSTEM_CMD[@]}" stop netagent

# Install executable
sudo install -m 0700 -C -t /opt/banyan ${DIRBIN}/netagent

if [[ $overwrite -eq 1 ]]; then
	# Install configuration
	sudo install -m 0600 -C -t /opt/banyan ${DIR}/config.yaml
	rm ${DIR}/config.yaml
fi

# Use process id 1 to determine init system, default to upstart
if [[ $(ps -p1 | grep -o systemd) == "systemd" ]]; then
	echo "Looks like a systemd system"
	sudo install -m 0644 "${DIRETC}/netagent.service.tpl" /lib/systemd/system/netagent.service
	check_error "install -m 0644 ${DIRETC}/netagent.service.tpl /lib/systemd/system/netagent.service"
	"${INIT_SYSTEM_CMD[@]}" enable netagent
	"${INIT_SYSTEM_CMD[@]}" daemon-reload
else
	echo "Looks like an upstart system"
	sudo install -m 0644 "${DIRETC}/netagent.conf.tpl" /etc/init/netagent.conf
	check_error "install -m 0644 ${DIRETC}/netagent.conf.tpl /etc/init/netagent.conf"
fi

"${INIT_SYSTEM_CMD[@]}" stop netagent
"${INIT_SYSTEM_CMD[@]}" start netagent
"${INIT_SYSTEM_CMD[@]}" status netagent
