#!/bin/bash

# Lib file with common functions for xivo-upgrade and mds-upgrade scripts

pre_stop() {
    local type="${1}"; shift

    /usr/bin/xivo-run-upgrade-scripts "${type}" pre-stop
}

post_stop() {
    local type="${1}"; shift

    /usr/bin/xivo-run-upgrade-scripts "${type}" post-stop
}

pre_start() {
    local type="${1}"; shift

    /usr/bin/xivo-run-upgrade-scripts "${type}" pre-start
}
post_start() {
    local type="${1}"; shift

    /usr/bin/xivo-run-upgrade-scripts "${type}" post-start
}

debian_version_installed() {
    cut -d '.' -f 1 /etc/debian_version
}

is_buster() {
    [ "$(debian_version_installed)" -eq 10 ]
}

is_bullseye() {
    [ "$(debian_version_installed)" -eq 11 ]
}

change_sources_list() {
    local old_distrib="$1"; shift
    local new_distrib="$1"; shift
    local source_list_file="$1"; shift

    sed -i "s/${old_distrib}/${new_distrib}/" "${source_list_file}"
}

switch_to_bullseye() {
    # Switch to Bullseye
    change_sources_list 'buster' 'bullseye' '/etc/apt/sources.list'
    change_sources_list 'buster' 'bullseye' '/etc/apt/sources.list.d/docker.list'
    add_postgresql_sources_list 'bullseye'
    # Fix the security repo name change
    change_sources_list 'bullseye\/updates' 'bullseye-security' '/etc/apt/sources.list'
    # Ensure bullseye backports are present
    add_distribution_sources_list "bullseye-backports"
}

add_postgresql_sources_list() {
    local distribution="${1:-bullseye}"; shift

	cat > /etc/apt/sources.list.d/pgdg.list <<-EOF
	deb http://apt.postgresql.org/pub/repos/apt/ ${distribution}-pgdg main
	EOF

    add_key_in_keyring "https://apt.postgresql.org/pub/repos/apt/ACCC4CF8.asc" "/etc/apt/trusted.gpg.d/apt.postgresql.org.gpg"
}

add_xivo_apt_conf() {
    if [ -f /etc/apt/apt.conf.d/90pf ]; then
        echo "Deleting old apt configuration file: etc/apt/apt.conf.d/90pf"
        rm -f /etc/apt/apt.conf.d/90pf
    fi
    echo "Installing new apt configuration file: /etc/apt/apt.conf.d/90xivo"

	cat > /etc/apt/apt.conf.d/90xivo <<-EOF
	Aptitude::Recommends-Important "false";
	APT::Install-Recommends "false";
	APT::Install-Suggests "false";
	EOF
}

check_source_exists() {
    local type="$1"; shift
    local distribution="$1"; shift
    local component="$1"; shift
    local list="$1"; shift

    grep -Prq "^\s*${type}\s.+\s${distribution}\s+${component}\b" ${list}
}

add_distribution_sources_list() {
    local distribution="${1:-bullseye-backports}"

    if ! check_source_exists deb "${distribution}" main "/etc/apt/sources.list*"; then
            cat >> /etc/apt/sources.list <<-EOF
			
			deb http://ftp.fr.debian.org/debian ${distribution} main
			EOF
    fi
    if ! check_source_exists deb-src "${distribution}" main "/etc/apt/sources.list*"; then
            cat >> /etc/apt/sources.list <<-EOF
			deb-src http://ftp.fr.debian.org/debian ${distribution} main
			EOF
    fi
}

ask_to_continue_upgrade() {
    local force="${1}"; shift
    local answer

    if [ "${force}" -eq 0 ]; then
        read -p 'Would you like to upgrade your system (all services will be restarted) [Y/n]? ' answer
        answer="${answer:-Y}"
        if [ "$answer" != 'y' ] && [ "$answer" != 'Y' ]; then
            exit
        fi
    fi
}

display_system_upgrade_notice() {
	cat <<-EOF
	****************************************************************************
	*                                                                          *
	*  The Debian GNU/Linux system will be upgraded                            *
	*    from version 10 (Buster)                                              *
	*    to   version 11 (Bullseye).                                           *
	*  Hence, this upgrade will be longer than other upgrades.                 *
	*                                                                          *
	*  You will need to RESTART the machine after the upgrade.                 *
	*                                                                          *
	****************************************************************************
	EOF
}

display_buster_to_bullseye_upgrade_reboot_notice() {
	cat <<-EOF
	**********************************************************
	*  WARNING: the system was upgraded                      *
	*    from Debian 10 (Buster)                             *
	*    to   Debian 11 (Bullseye)                           *
	*                                                        *
	*  You must RESTART the machine to finalize the upgrade  *
	*                                                        *
	**********************************************************
	EOF
}

is_grub_broken() {
    if [ -f /boot/grub/device.map ]; then
        for disk in $(awk '{print $2}' /boot/grub/device.map) ; do
            if [ ! -e "$disk" ] ; then
                return 0
            fi
        done
    fi
    install_device=$(debconf-show grub-pc | grep 'grub-pc/install_devices:' | cut -b3- | cut -f2 -d\ )
    if [ "$install_device" ] && [ ! -e "$install_device" ]; then
        return 0
    fi
    return 1
}

check_if_grub_is_broken() {
    if is_grub_broken; then
		cat <<-EOF
		*********************************************
		* You must install GRUB BEFORE rebooting:   *
		*                                           *
		* # apt install grub-pc                 *
		* # rm /boot/grub/device.map                *
		* # grub-install /dev/<boot_device>         *
		* # shutdown -r now                         *
		*                                           *
		* If you are often getting this error, you  *
		* should run "dpkg-reconfigure grub-pc".    *
		*                                           *
		*********************************************
		EOF
    fi
}

is_postgres_running_on_port() {
    local pgpass="${1:-proformatique}"; shift
    local dbhost="${1:-localhost}"; shift
    local dbport="${1:-5432}"; shift
    local dbusername="${1:-postgres}"; shift
    local dbname="${1:-asterisk}"; shift

    result=$(PGPASSWORD=${pgpass} psql -h "${dbhost}" -p ${dbport} -U ${dbusername} -qAtc "select 1 from pg_catalog.pg_database WHERE datname='${dbname}'" 2>/dev/null)

    [ $? -eq 0 ] && [ "$result" = "1" ]
}

wait_for_postgres() {
    local pgpass="${1:-proformatique}"; shift
    local dbhost="${1:-localhost}"; shift
    local dbport="${1:-5432}"; shift
    local dbusername="${1:-postgres}"; shift
    local dbname="${1:-asterisk}"; shift

    echo "Waiting for database $dbname on port $dbport."
    echo -n "It should not take more than a few minutes..."

    while true; do
        if is_postgres_running_on_port "$pgpass" "$dbhost" "$dbport" "$dbusername" "$dbname"; then
            break
        else
            sleep 1
            echo -n "."
        fi
    done
    echo
}

is_xivoucaddon() {
    [ -f /var/lib/xivo/uc_enabled ]
}

is_key_in_keyring() {
    local keyid="${1}"; shift
    local keyringfile="${1}"; shift

    if gpg --batch --no-tty --keyring "${keyringfile}" --list-keys --with-colons | grep -q "${keyid}"; then
        return 0
    else
        return 1
    fi
}

add_key_in_keyring() {
    local keyurl="${1}"; shift
    local keyringfile="${1}"; shift

    echo "Removing file ${keyringfile}"
    rm -rf "${keyringfile}"
    touch "${keyringfile}"
    echo "Adding GPG key from ${keyurl} to ${keyringfile}..."
    curl -fsSL "${keyurl}" | gpg --dearmor | tee "${keyringfile}" >/dev/null
}

remove_key_from_apt_keyring() {
    local keyid=${1}; shift

    echo "Removing key ${keyid} from /etc/apt/trusted.gpg"
    apt-key del "${keyid}"
}
