#!/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

init_log

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"

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_install_xivocc_type() {
	XIVOCC_TYPE=$(whiptail --title "XiVO CC Installation Type" --radiolist \
	"Select the type of installation:" 15 65 3 \
	"full"    "Full installation (app + backend)" ON \
	"app"     "Application only (XUC services, Nginx, XUCMGT)" OFF \
	"backend" "Backend only (Recording and statistics)" OFF 3>&1 1>&2 2>&3)
}

ask_xivo_ip() {
	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}"
}

ask_xivocc_ip() {
	interfaces=$(ip -br -o link show | awk -F' ' '{print $1}' | grep -vE "lo|docker0|br|veth")

	options=()
	for iface in $interfaces; do
		ip_addr=$(ip -br -4 addr show "$iface" | awk -F' ' '{print $3}' | cut -d/ -f1)
		ip_display=${ip_addr:-"No IP"}
		options+=("$iface" "$ip_display")
	done

	# Add manual entry option at the end
	options+=("manual" "Enter IP address manually")

	# Show the menu
	choice=$(whiptail --title "XIVOCC IP Selection" --menu "Select the XIVOCC IP address or enter it manually:" 15 65 6 "${options[@]}" 3>&1 1>&2 2>&3)

	# Handle manual input
	if [ "$choice" = "manual" ]; then
		XUC_HOST=$(whiptail --inputbox "Enter the XIVOCC IP address:" 8 65 3>&1 1>&2 2>&3)
	else
		XUC_HOST=$(ip -br -4 addr show "$choice" | awk -F' ' '{print $3}' | cut -d/ -f1)
	fi

	echo "Selected IP address: $XUC_HOST"
}

ask_xuc_fqdn() {
    if whiptail --title "FQDN for XUC" --yesno "Do you want to enter a FQDN for the XUC?" 8 60; then
        XUC_FQDN=$(whiptail --inputbox "Enter the FQDN for the XUC:" 8 65 3>&1 1>&2 2>&3)
        echo "FQDN entered: $XUC_FQDN"
    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_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_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 XiVOCC Type choices
	ask_install_xivocc_type

	# Ask XiVO Network Questions
	ask_xivo_ip
	ask_xivocc_ip

	# Ask XiVOCC specify Questions type 'full' and 'app'
	if [ "$XIVOCC_TYPE" != "backend" ]; then
		ask_xuc_fqdn
	fi

	# Ask XiVOCC backend if type app
	if [ "$XIVOCC_TYPE" == "app" ]; then
		XIVOCC_BACKEND=$(whiptail --inputbox "Enter the XiVOCC Backend address: " 8 50 3>&1 1>&2 2>&3)
	fi

	# 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 specify Questions type 'full' and 'backend'
	if [ "$XIVOCC_TYPE" != "app" ]; then
		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)
	fi
}

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
		log "\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}

		log "\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
		log "\e[1;33mAlias dcomp was replaced by xivocc-dcomp script\e[0m"
		log "\e[1;31mPlease run unalias dcomp\e[0m"
	fi
}

set_xivocc_dist_in_custom_env() {
    if [ -z XIVOCC_DIST ]; then
        echo "XIVOCC_DIST=${XIVOCC_DIST}" >> ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
    fi
}

set_global_env_file() {
	{
		echo "XIVOCC_TYPE=${XIVOCC_TYPE}"
		echo "XIVO_HOST=${XIVO_HOST}"
		echo "CONFIG_MGT_HOST=${XIVO_HOST}"
		echo "CONFIG_MGT_PORT=9100"
		echo "REPORTING_HOST=${XIVOCC_BACKEND:-$XUC_HOST}"
	} >${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
}

set_specific_variables_by_installation_type() {
	if [ "${XIVOCC_TYPE}" == "app" ]; then
		{
			echo "XUC_HOST=${XUC_FQDN:-$XUC_HOST}"
			echo "XIVO_AMI_SECRET=${XIVO_AMI_SECRET}"
			echo "RECORDING_SERVER_HOST=${XIVOCC_BACKEND}"
			echo "RECORDING_SERVER_PORT=9400"
		} >>${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
	elif [ "${XIVOCC_TYPE}" == "backend" ]; then
		{
			echo "WEEKS_TO_KEEP=${WEEKS_TO_KEEP}"
			echo "RECORDING_WEEKS_TO_KEEP=${RECORDING_WEEKS_TO_KEEP}"
		} >>${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
	else
		{
			echo "XUC_HOST=${XUC_FQDN:-$XUC_HOST}"
			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}
	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}
}

source_xivocc_dist() {
    if [ -f ${COMPOSE_PATH}/${CUSTOM_ENV_FILE} ]; then
        # shellcheck disable=SC1090
        source ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}

        XIVOCC_DIST=${XIVOCC_DIST}
    fi
}

generate_custom_env_file() {
	log "\e[1;33mGenerating ${CUSTOM_ENV_FILE} configuration file\e[0m"
	source_xivocc_dist
	set_global_env_file
	set_xivocc_dist_in_custom_env
	set_specific_variables_by_installation_type
	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
		log "\\e[1;33mWARN: Postgres container $PGXIVOCC was not found on this host.\\e[0m"
		log "\\e[1;33m  - If this is normal, you can ignore this warning.\\e[0m"
		log "\\e[1;33m  - Otherwise, if $PGXIVOCC container should be on this host, you MUST NOT restart the containers\\e[0m"
		log "\\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}
}

check_for_spagobi_export_directory() {
	spagobi_export_directory="/var/backups/spagobi"
	if [[ -d "$spagobi_export_directory" ]]; then
		count="$( find "$spagobi_export_directory" -mindepth 1 -maxdepth 1 | wc -l )"
		if [[ "$count" -eq 0 ]] ; then
			echo "Removing empty spagobi backup directory"
			rm -r "$spagobi_export_directory"
		else
			echo "Spagobi backup directory non-empty in /var/backups/spagobi, skipping removal."
			echo "Clean up manually after upgrade if no longer needed."
		fi
	fi
}

generate_override_configuration() {
	if [ "$XIVOCC_TYPE" == "app" ]; then
		cp ${COMPOSE_PATH}/template/00-xivocc-disable-rep-rec.override.yml ${COMPOSE_PATH}/
	elif [ "$XIVOCC_TYPE" == "backend" ]; then
		cp ${COMPOSE_PATH}/template/00-xivocc-disable-app.override.yml ${COMPOSE_PATH}/
	fi
}

validate_custom_env_vars() {
    local type="$1"
    local file="${COMPOSE_PATH}/${CUSTOM_ENV_FILE}"
    local temp_file="${file}.tmp"

    declare -A allowed_vars_app=(
        [XUC_HOST]=1
        [XIVO_AMI_SECRET]=1
        [RECORDING_SERVER_HOST]=1
        [RECORDING_SERVER_PORT]=1
        [REPORTING_HOST]=1
    )
    declare -A allowed_vars_backend=(
        [WEEKS_TO_KEEP]=1
        [RECORDING_WEEKS_TO_KEEP]=1
        [REPORTING_HOST]=1
    )
    declare -A allowed_vars_full=(
        [XUC_HOST]=1
        [WEEKS_TO_KEEP]=1
        [RECORDING_WEEKS_TO_KEEP]=1
        [XIVO_AMI_SECRET]=1
        [REPORTING_HOST]=1
    )

    local -a required_vars=()
    case "$type" in
        app)     required_vars=(RECORDING_SERVER_HOST RECORDING_SERVER_PORT REPORTING_HOST) ;;
        backend) required_vars=(REPORTING_HOST) ;;
        full)    required_vars=(REPORTING_HOST) ;;
        *) log "\e[1;31mERROR: Unknown XIVOCC_TYPE '${type}'.\e[0m"; return 1 ;;
    esac

    declare -A all_known_vars
    for key in "${!allowed_vars_app[@]}" "${!allowed_vars_backend[@]}" "${!allowed_vars_full[@]}"; do
        all_known_vars["$key"]=1
    done

    local -n allowed_vars
    case "$type" in
        app) allowed_vars=allowed_vars_app ;;
        backend) allowed_vars=allowed_vars_backend ;;
        full) allowed_vars=allowed_vars_full ;;
    esac

    declare -A found_vars
    declare -A values
    declare -A skip_echo
    local missing_var_added=false

    local xuc_host=""
    local reporting_host=""
    local recording_host=""
    local recording_server_port=""

    is_ipv4() {
        [[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]
    }

    {
        while IFS='=' read -r key val || [[ -n "$key" ]]; do
            if [[ -z "${key// }" ]]; then
                continue
            elif [[ "$key" =~ ^[[:space:]]*# ]]; then
                echo "${key}${val:+=$val}"
                continue
            fi

            key=$(echo -n "$key" | xargs)
            val=${val%$'\r'}

            values["$key"]="$val"
            found_vars["$key"]=1

            case "$key" in
                XUC_HOST) xuc_host="$val" ;;
                REPORTING_HOST) reporting_host="$val" ;;
                RECORDING_SERVER_HOST) recording_host="$val" ;;
                RECORDING_SERVER_PORT) recording_server_port="$val" ;;
            esac

            if [[ ${all_known_vars[$key]+_} ]]; then
                if [[ "$key" == "XIVOCC_TYPE" || ${allowed_vars[$key]+_} ]]; then
                    case "$type:$key" in
                        app:RECORDING_SERVER_HOST|app:REPORTING_HOST)
                            if [[ -z "$val" ]]; then
                                skip_echo["$key"]=1
                            elif [[ $(is_ipv4 "$val"; echo $?) -eq 0 ]]; then
                                echo "${key}=${val}"
                            else
                                skip_echo["$key"]=1
                                log "\e[1;33mWARN: '${key}' is not an IP address. Resetting its value in ${CUSTOM_ENV_FILE}.\e[0m" true
                            fi
                            ;;
                        app:RECORDING_SERVER_PORT)
                            if [[ -z "$val" ]]; then
                                skip_echo["$key"]=1
                            else
                                echo "${key}=${val}"
                            fi
                            ;;
                        backend:REPORTING_HOST)
                            if [[ -z "$val" ]]; then
                                skip_echo["$key"]=1
                            elif [[ $(is_ipv4 "$val"; echo $?) -eq 0 ]]; then
                                echo "${key}=${val}"
                            else
                                skip_echo["$key"]=1
                            fi
                            ;;
                        full:REPORTING_HOST)
                            if [[ -z "$val" ]]; then
                                skip_echo["$key"]=1
                            else
                                echo "${key}=${val}"
                            fi
                            ;;
                        *)
                            echo "${key}=${val}"
                            ;;
                    esac
                else
                    log "\e[1;33mWARN: '${key}' is not used in type '${type}', removing from ${CUSTOM_ENV_FILE}.\e[0m" true
                fi
            else
                echo "${key}=${val}"
            fi
        done < "$file"

        for var in "${!allowed_vars[@]}"; do
            local skip_required=false
            for r in "${required_vars[@]}"; do [[ "$var" == "$r" ]] && skip_required=true && break; done
            $skip_required && continue

            if [[ -z "${found_vars[$var]+_}" ]]; then
                log "\e[1;34mINFO: Adding optional variable '${var}' (empty) to ${CUSTOM_ENV_FILE}.\e[0m" true
                echo "${var}="
                missing_var_added=true
            fi
        done

        for r in "${required_vars[@]}"; do
            case "$type:$r" in
                app:RECORDING_SERVER_HOST|app:REPORTING_HOST)
                    if [[ -z "${found_vars[$r]+_}" || -n "${skip_echo[$r]+_}" ]]; then
                        log "\e[1;34mINFO: Adding required '${r}' (empty) for type '${type}' in ${CUSTOM_ENV_FILE}.\e[0m" true
                        echo "${r}="
                        missing_var_added=true
                    fi
                    ;;
                app:RECORDING_SERVER_PORT)
                    if [[ -z "${found_vars[$r]+_}" || -n "${skip_echo[$r]+_}" || -z "$recording_server_port" ]]; then
                        log "\e[1;34mINFO: Setting '${r}' to default value '9400' in ${CUSTOM_ENV_FILE}.\e[0m" true
                        echo "${r}=9400"
                    fi
                    ;;
                backend:REPORTING_HOST)
                    if [[ -z "${found_vars[$r]+_}" || -n "${skip_echo[$r]+_}" ]]; then
                        if [[ -n "$xuc_host" && $(is_ipv4 "$xuc_host"; echo $?) -eq 0 ]]; then
                            log "\e[1;34mINFO: Setting '${r}' from 'XUC_HOST=${xuc_host}' in ${CUSTOM_ENV_FILE}.\e[0m" true
                            echo "${r}=${xuc_host}"
                        else
							log "\e[1;34mINFO: Adding required '${r}' (empty) for type '${type}' in ${CUSTOM_ENV_FILE}.\e[0m" true
							echo "${r}="
							missing_var_added=true
                        fi
                    fi
                    ;;
                full:REPORTING_HOST)
                    if [[ -z "${found_vars[$r]+_}" || -n "${skip_echo[$r]+_}" ]]; then
                        if [[ -n "$xuc_host" ]]; then
                            log "\e[1;34mINFO: Setting '${r}' from 'XUC_HOST=${xuc_host}' in ${CUSTOM_ENV_FILE}.\e[0m" true
                            echo "${r}=${xuc_host}"
                        else
                            log "\e[1;33mWARN: '${r}' is missing and 'XUC_HOST' is not set. Leaving it empty in ${CUSTOM_ENV_FILE}.\e[0m" true
                            echo "${r}="
                            missing_var_added=true
                        fi
                    fi
                    ;;
            esac
        done

        if $missing_var_added; then
            log "\e[1;33mWARN: Some variables were added with empty in ${CUSTOM_ENV_FILE}.\e[0m" true
            log "\e[1;33mWARN: Please validate or configure them before running 'xivocc-dcomp up -d --remove-orphans'.\e[0m" true
        fi

    } > "$temp_file"

    mv "$temp_file" "$file"
    log "\e[1;32mINFO: ${CUSTOM_ENV_FILE} cleaned and validated for type '${type}'.\e[0m"
}

case "$1" in
configure)
	##install path
	if [ -z "$2" ]; then
		if ! hostname --fqdn; then
			log "\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
		generate_override_configuration

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

		# Specific config if type is 'full' or 'backend'
		if [ "$XIVOCC_TYPE" != "app" ]; then
			# Recording config
			mkdir -p /var/spool/recording-server
			chown daemon:daemon /var/spool/recording-server
			chmod 760 /var/spool/recording-server
		fi

		# Specific config if type is 'full' or 'app'
		if [ "$XIVOCC_TYPE" != "backend" ]; then
			# Self-signed certificate for NGINX
			create_nginx_certificate
		fi

		# Operation that need XiVO PBX to be configured
		if [ "$CONFIGURE_REPLY" = true ]; then
			xivocc_configures_xivo_post_wizard
		else
			log "\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

		if [ -n "$XUC_FQDN" ]; then
			log "\e[1;33mThe FQDN '${XUC_FQDN}' has been set for XUC_HOST in ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}\e[0m"
		else
			log "\e[1;33mNow you can replace XUC_HOST (XUC server IP address) by a FQDN in ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}\e[0m"
		fi
		if [ "$CONFIGURE_REPLY" = false ]; then
			log "\e[1;33mYou chose not to configure XiVO PBX\e[0m"
			log "\e[1;33mPlease follow the 'Manual configuration' documentation page to complete the installation\e[0m"
			log "\e[1;33mAnd start with command xivocc-dcomp up -d\e[0m"
		else
			log "\e[1;33mPlease start with command xivocc-dcomp up -d\e[0m"
		fi
		log "\e[1;33mThen open https://${XUC_FQDN:-$XUC_HOST} in your browser\e[0m"

		echo "You can check logs at $LOG_FILE if needed."
	##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
			log "\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"
				log "\\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" "<<" "2026.04.01"; then
			check_for_spagobi_export_directory
		fi

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

		if dpkg --compare-versions "$previous_version" "<<" "2025.07.00"; then
			# validate XIVOCC_TYPE and purge vars
			if grep -q XIVOCC_TYPE ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}; then
				XIVOCC_TYPE=$(grep -oP -m 1 '^\s*XIVOCC_TYPE=\K.*' "${COMPOSE_PATH}/${CUSTOM_ENV_FILE}")
			else
				XIVOCC_TYPE="full"
				sed -i "1iXIVOCC_TYPE=${XIVOCC_TYPE}" ${COMPOSE_PATH}/${CUSTOM_ENV_FILE}
				log "\\e[1;33mWARN: XIVOCC_TYPE variable has been automatically set to 'full' (fully installed).\\e[0m"
			fi
			validate_custom_env_vars "$XIVOCC_TYPE"
		fi
		# Add the override corresponding to the configuration
		generate_override_configuration
		echo "You can check logs at $LOG_FILE if needed."
	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
