#!/bin/bash
# postinst script for xivocc-installer
#
# see: dh_installdeb(1)

# shellcheck source=install/usr/bin/xivocc-installer-lib/xivo-configuration-helper.sh
source "/usr/bin/xivocc-installer-lib/xivo-configuration-helper.sh"

set -e

COMPOSE_PATH="/etc/docker/compose"
COMPOSE_FILE="docker-xivocc.yml"
ENV_FILE=".env"
CUSTOM_ENV_FILE="custom.env"

INSTALLATION_TYPE="CC"
XIVOCC_CONFIG_SCRIPT_LOCAL="/usr/bin/configure-pbx"
XIVOCC_CONFIG_SCRIPT_REMOTE="/usr/bin/xivocc-configure-xivopbx"
XUC_PORT=8090

RESTART_REPLY=false
CONFIGURE_REPLY=false

POSTGRESQL_DATA_DIR=/var/lib/postgresql/data
PGXIVOCC="xivocc_pgxivocc_1"
PLAY_AUTH_TOKEN=sreSgq6BiEzKR80f03WtFOyzXirnJlzsaUXwkQhHsBReaVj5UJal5323dY6GBtRK

get_xivo_host() {
	if [ -f ${COMPOSE_PATH}/${ENV_FILE} ]; then
		XIVO_HOST=$(grep -oP -m 1 '^\s*XIVO_HOST=\K.*' ${COMPOSE_PATH}/${ENV_FILE})
	else
		XIVO_HOST=$(whiptail --title "XiVO PBX IP address not found" --inputbox "Enter the XiVO PBX IP address: " 8 50 3>&1 1>&2 2>&3)
	fi
}

get_xuc_host() {
	if [ -f ${COMPOSE_PATH}/${ENV_FILE} ]; then
		XUC_HOST=$(grep -oP -m 1 '^\s*XUC_HOST=\K.*' ${COMPOSE_PATH}/${ENV_FILE})
	else
		XUC_HOST=$(whiptail --title "XUC server IP address not found" --inputbox "Enter this machine's external IP address: " 8 50 3>&1 1>&2 2>&3)
	fi
}

get_weeks() {
	if [ -f ${COMPOSE_PATH}/${ENV_FILE} ]; then
		WEEKS_TO_KEEP=$(grep -oP -m 1 '^\s*WEEKS_TO_KEEP=\K.*' ${COMPOSE_PATH}/${ENV_FILE})
	else
		WEEKS_TO_KEEP=$(whiptail --title "Weeks to keep statistics not found" --inputbox "Enter the number of weeks to keep the statistics. " 8 50 3>&1 1>&2 2>&3)
	fi
}

get_recording_weeks() {
	if [ -f ${COMPOSE_PATH}/${ENV_FILE} ]; then
		RECORDING_WEEKS_TO_KEEP=$(grep -oP -m 1 '^\s*RECORDING_WEEKS_TO_KEEP=\K.*' ${COMPOSE_PATH}/${ENV_FILE})
	else
		RECORDING_WEEKS_TO_KEEP=$(whiptail --title "Weeks to keep recordings not found" --inputbox "Enter the number of weeks to keep the recording files." 8 50 3>&1 1>&2 2>&3)
	fi
}

get_ami_secret() {
	if [ -f ${COMPOSE_PATH}/${ENV_FILE} ]; then
		XIVO_AMI_SECRET=$(grep -oP -m 1 '^\s*XIVO_AMI_SECRET=\K.*' ${COMPOSE_PATH}/${ENV_FILE})
	else
		XIVO_AMI_SECRET=$(whiptail --title "AMI secret password not found" --inputbox "Please enter the XiVO PBX AMI secret." 8 50 3>&1 1>&2 2>&3)
	fi
}

remove_generated_logrotate() {
	rm -f /etc/logrotate.d/docker-container
}

create_nginx_certificate() {
	SSLDIR=/etc/docker/nginx/ssl
	mkdir -p $SSLDIR
	openssl req -nodes -newkey rsa:2048 -keyout $SSLDIR/xivoxc.key -out $SSLDIR/xivoxc.csr -subj "/C=FR/ST=Rhone-Alpes/L=Limonest/O=Avencall/CN=$(hostname --fqdn)"
	openssl x509 -req -days 3650 -in $SSLDIR/xivoxc.csr -signkey $SSLDIR/xivoxc.key -out $SSLDIR/xivoxc.crt
}

create_secret() {
	local secret_length="${1}"
	shift
	local generated_secret

	generated_secret=$(tr </dev/urandom -dc A-Za-z0-9 | head -c "${secret_length}")
	echo "${generated_secret}"
}

remove_key_in_custom_env() {
	local key_to_remove="${1}"
	shift

	sed -e "/^${key_to_remove}/d" -i ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
}

ask_restart_xivo() {
	if (whiptail --title "Restart XiVO PBX" --yesno "XiVO PBX will be reconfigured during the installation and must be restarted. Do you want to restart it during the installation?" 8 78); then
		RESTART_REPLY=true
	else
		RESTART_REPLY=false
	fi
}

ask_configure_xivo() {
	if (whiptail --title "Configure XiVO PBX during XiVO $INSTALLATION_TYPE setup" --yesno "Would you like to configure your XiVO PBX? Consider the already present XiVO $INSTALLATION_TYPE configuration please." 8 78); then
		CONFIGURE_REPLY=true
	else
		CONFIGURE_REPLY=false
	fi
}

ask_questions() {
	# General message
	whiptail --title "XiVO CC - XiVO PBX Configuration Details" --msgbox "You will be asked XiVO PBX & XiVO CC configuration questions." 8 50
	# Ask XiVO Network Questions
	echo "Ask for XiVO PBX IP"
	XIVO_HOST=$(whiptail --inputbox "Enter the XiVO PBX IP address: " 8 50 3>&1 1>&2 2>&3)
	echo "Got ${XIVO_HOST}"
	echo "Ask for XiVO CC IP"
	XUC_HOST=$(whiptail --inputbox "Enter this machine's external IP address: " 8 65 3>&1 1>&2 2>&3)
	echo "Got ${XUC_HOST}"

	# Ask whether to configure XiVO PBX with XUC
	ask_configure_xivo

	# Ask when to restart XiVO PBX
	if [ "$CONFIGURE_REPLY" = true ]; then
		ask_restart_xivo
	fi

	# ASk XiVOCC Generic Questions
	WEEKS_TO_KEEP=$(whiptail --inputbox "Enter the number of weeks to keep for the statistics: " 8 50 3>&1 1>&2 2>&3)
	RECORDING_WEEKS_TO_KEEP=$(whiptail --inputbox "Enter the number of weeks to keep for the recording files: " 8 50 3>&1 1>&2 2>&3)
}

migrate_env_to_custom_env() {
	get_xivo_host
	get_xuc_host
	get_weeks
	get_recording_weeks
	get_ami_secret

	if [ -f ${COMPOSE_PATH}/${ENV_FILE} ]; then
		echo -e "\e[1;33mGenerating ${CUSTOM_ENV_FILE} configuration file from ${ENV_FILE} file\e[0m"
		cp -f ${COMPOSE_PATH}/${ENV_FILE} ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
		sed -e '/XIVOCC_TAG/d' -i ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
		sed -e '/XIVOCC_DIST/d' -i ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}

		echo -e "\e[1;33mRenaming ${ENV_FILE} file to ${ENV_FILE}.dpkg-old\e[0m"
		mv -f ${COMPOSE_PATH}/${ENV_FILE} ${COMPOSE_PATH}/${ENV_FILE}.dpkg-old
	else
		generate_custom_env_file
	fi

	# Migration specific - see #816
	if [ -n "$ENFORCE_MANAGER_SECURITY" ]; then
		echo "ENFORCE_MANAGER_SECURITY=${ENFORCE_MANAGER_SECURITY}" >>${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
	fi
}

remove_dcomp_alias() {
	if (grep -oP -m 1 '^alias dcomp=' ~/.bashrc &>/dev/null); then
		sed -e '/alias dcomp=/ s/^#*/#/' -i ~/.bashrc
		echo -e "\e[1;33mAlias dcomp was replaced by xivocc-dcomp script\e[0m"
		echo -e "\e[1;31mPlease run unalias dcomp\e[0m"
	fi
}

set_play_secret_in_custom_env_file() {
	local play_secret
	play_secret=$(create_secret "64")
	echo "APPLICATION_SECRET=${play_secret}" >>${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
}

set_play_auth_token_in_custom_env_file() {
	echo "PLAY_AUTH_TOKEN=${PLAY_AUTH_TOKEN}" >>${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
}

set_xuc_auth_secret_in_custom_env_file() {
	local xuc_auth_secret
	xuc_auth_secret=$(create_secret "64")
	echo "XUC_AUTH_SECRET=${xuc_auth_secret}" >>${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
}

set_default_deprecated_api_host() {
	echo "DEPRECATED_API_HOST=${XIVO_HOST}" >>${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
}

generate_custom_env_file() {
	echo -e "\e[1;33mGenerating ${CUSTOM_ENV_FILE} configuration file\e[0m"
	{
		echo "XIVO_HOST=${XIVO_HOST}"
		echo "XUC_HOST=${XUC_HOST}"
		echo "CONFIG_MGT_HOST=${XIVO_HOST}"
		echo "CONFIG_MGT_PORT=9100"
		echo "XUC_PORT=${XUC_PORT}"
		echo "WEEKS_TO_KEEP=${WEEKS_TO_KEEP}"
		echo "RECORDING_WEEKS_TO_KEEP=${RECORDING_WEEKS_TO_KEEP}"
		echo "XIVO_AMI_SECRET=${XIVO_AMI_SECRET}"
	} >${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
	set_play_secret_in_custom_env_file
	set_play_auth_token_in_custom_env_file
	set_xuc_auth_secret_in_custom_env_file
	set_default_deprecated_api_host
}

set_configmgt_in_custom_env_file() {
	XIVO_HOST_FROM_CUSTOM_ENV=$(grep -oP -m 1 '^\s*XIVO_HOST=\K.*' ${COMPOSE_PATH}/${CUSTOM_ENV_FILE})
	echo "CONFIG_MGT_HOST=${XIVO_HOST_FROM_CUSTOM_ENV}" >>${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
	echo "CONFIG_MGT_PORT=9100" >>${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
}

rename_recording_server_host_key() {
	sed -e 's/RECORDING_SERVER_HOST=recording$/RECORDING_SERVER_HOST=recording_server/g' -i ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
}

migrate_postgres_data_to_bind() {
	local postgres
	postgres=$(docker ps -aq --filter "name=$PGXIVOCC")
	if [ -n "$postgres" ]; then
		echo "Migrating postgres database data from docker volume to bind"
		docker stop $PGXIVOCC

		POSTGRESQL_DATA_DOCKER_DIR=$(docker inspect ${PGXIVOCC} -f '{{range .Mounts}}{{if (eq .Destination "/var/lib/postgresql/data")}}{{.Source}}{{end}}{{end}}')
		mkdir -p $POSTGRESQL_DATA_DIR
		mv "${POSTGRESQL_DATA_DOCKER_DIR}/*" $POSTGRESQL_DATA_DIR
		chmod 700 $POSTGRESQL_DATA_DIR
		docker rm -f $PGXIVOCC
	else
		echo -e "\\e[1;33mWARN: Postgres container $PGXIVOCC was not found on this host.\\e[0m"
		echo -e "\\e[1;33m  - If this is normal, you can ignore this warning.\\e[0m"
		echo -e "\\e[1;33m  - Otherwise, if $PGXIVOCC container should be on this host, you MUST NOT restart the containers\\e[0m"
		echo -e "\\e[1;33m    before making sure that the db data is moved from the container to the host.\\e[0m"
	fi
}

rename_auth_expires_to_auth_cti_expires() {
	sed -e 's/AUTH_EXPIRES/AUTH_CTI_EXPIRES/g' -i ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
}

create_spagobi_export_directory() {
	spagobi_export_directory="/var/backups/spagobi"
	mkdir -p $spagobi_export_directory
	chown -R daemon:daemon $spagobi_export_directory
}

case "$1" in
configure)
	##install path
	if [ -z "$2" ]; then
		if ! hostname --fqdn; then
			echo -e "\e[1;31mFQDN not set correctly, please check hostname and /etc/hosts. Exiting...\e[0m"
			exit 1
		fi

		if [ "$DEBIAN_FRONTEND" = "noninteractive" ] && [ -f "${COMPOSE_PATH}/${CUSTOM_ENV_FILE}" ]; then
			source_custom_env_file
		else
			ask_questions
		fi

		# Generic XiVO CC config
		mkdir -p ${COMPOSE_PATH}
		XIVO_AMI_SECRET=$(create_secret "11")
		generate_custom_env_file

		mkdir -p /var/log/xivocc
		chown -R daemon:daemon /var/log/xivocc

		create_spagobi_export_directory

		# Recording config
		mkdir -p /var/spool/recording-server
		chown daemon:daemon /var/spool/recording-server
		chmod 760 /var/spool/recording-server

		# Self-signed certificate for NGINX
		create_nginx_certificate

		# Operation that need XiVO PBX to be configured
		if [ "$CONFIGURE_REPLY" = true ]; then
			xivocc_configures_xivo_post_wizard
		else
			echo -e "\e[1;33mXiVO CC is installed. XiVO PBX was not configured, launch ${XIVOCC_CONFIG_SCRIPT_LOCAL} when you will be ready to configure the XiVO PBX\e[0m"
			exit 0
		fi

		cat <<-EOF
			XiVO CC is installed.
			If a pack reporting was previously installed with the old packaging system, please migrate the database first.
			If you are using XiVO CC with a version of XiVO below 15.15, please modify ${COMPOSE_PATH}/${COMPOSE_FILE} to use the proper ast11 images.
		EOF
		echo -e "\e[1;33mNow you can replace XUC_HOST (XUC server IP address) by FQDN in ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}\e[0m"
		if [ "$CONFIGURE_REPLY" = false ]; then
			echo -e "\e[1;33mYou chose not to configure XiVO PBX\e[0m"
			echo -e "\e[1;33mPlease follow the 'Manual configuration' documentation page to complete the installation\e[0m"
			echo -e "\e[1;33mAnd start with command xivocc-dcomp up -d\e[0m"
		else
			echo -e "\e[1;33mPlease start with command xivocc-dcomp up -d\e[0m"
		fi
		echo -e "\e[1;33mThen open http://$XUC_HOST (or FQDN) in your browser\e[0m"

	##upgrade path
	else
		previous_version=$2
		if [[ "$previous_version" < "2017.03" ]]; then
			ENFORCE_MANAGER_SECURITY=false
			migrate_env_to_custom_env
			remove_dcomp_alias
		fi
		if [[ "$previous_version" < "2017.11.06" ]]; then
			remove_generated_logrotate
		fi

		if [[ "$previous_version" < "2018.04" ]]; then
			set_configmgt_in_custom_env_file
		fi

		if dpkg --compare-versions "$previous_version" "<<" "2018.16.02"; then
			echo -e "\e[1;33mMove dbreplic to XiVO PBX...\e[0m"
			ask_restart_xivo
			get_xivo_host
			get_xuc_host

			install_package_on_xivo "${XIVO_HOST}"
			# Run the xuc setup script on XiVO PBX as update
			# shellcheck disable=SC2029
			ssh "root@${XIVO_HOST}" "bash ${XIVOCC_CONFIG_SCRIPT_REMOTE} \
                    -h $XUC_HOST \
                    -r $RESTART_REPLY \
                    -t ADD_DBREPLIC"
		fi

		if dpkg --compare-versions "$previous_version" "<<" "2019.02.00"; then
			set_play_secret_in_custom_env_file
		fi

		if dpkg --compare-versions "$previous_version" "<<" "2019.10.00"; then
			migrate_postgres_data_to_bind
		fi

		if dpkg --compare-versions "$previous_version" "<<" "2020.20.00"; then
			set_play_auth_token_in_custom_env_file
		fi

		if dpkg --compare-versions "$previous_version" "<<" "2021.15.00"; then
			if ! grep -q XUC_AUTH_SECRET ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}; then
				set_xuc_auth_secret_in_custom_env_file
			fi
		fi

		if dpkg --compare-versions "$previous_version" "<<" "2021.15.01"; then
			# Add XiVO IP in DEPRECATED_API_HOST
			get_xivo_host
			if grep -q DEPRECATED_API_HOST ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}; then
				remove_key_in_custom_env "DEPRECATED_API_HOST"
				echo -e "\\e[1;33mWARN: DEPRECATED_API_HOST variable has been automatically changed to $XIVO_HOST.\\e[0m"
			fi
			set_default_deprecated_api_host
			# Fix pwd length generated for Helios.00
			if dpkg --compare-versions "$previous_version" ">=" "2021.15.00"; then
				if grep -q XUC_AUTH_SECRET ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}; then
					remove_key_in_custom_env "XUC_AUTH_SECRET"
					set_xuc_auth_secret_in_custom_env_file
				fi
			fi
		fi

		if dpkg --compare-versions "$previous_version" "<<" "2023.05.00"; then
			get_xivo_host
			copy_custom_env_variable_from_xivo_to_xivocc "${XIVO_HOST}" "FLUENTD_SECRET"
		fi

		if dpkg --compare-versions "$previous_version" "<<" "2023.05.02"; then
			rename_auth_expires_to_auth_cti_expires
		fi

		if dpkg --compare-versions "$previous_version" "<<" "2023.05.02"; then
			rename_recording_server_host_key
		fi
		if dpkg --compare-versions "$previous_version" "<<" "2023.10.04"; then
			create_spagobi_export_directory
		fi

		if dpkg --compare-versions "$previous_version" "<<" "2024.10.02"; then
			remove_key_in_custom_env "USM_EVENT_AMQP_SECRET"
		fi

		echo -e "\e[1;33mPlease download new images with command xivocc-dcomp pull\e[0m"
		echo -e "\e[1;33mAnd start new containers with command xivocc-dcomp up -d --remove-orphans\e[0m"
	fi
	;;
abort-upgrade | abort-remove | abort-deconfigure) ;;
*)
	echo "postinst called with unknown argument '$1'" >&2
	exit 1
	;;
esac
# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.
#DEBHELPER#
exit 0
