#!/bin/bash
set -e

if [ $EUID != 0 ]; then
    echo "This script must be run as root" 1>&2
    exit 1
fi

PLUGIN_URL='http:\/\/provd.xivo.solutions\/plugins\/1\/stable\/'
PACKAGE_URL='http://mirror.xivo.solutions/debian/tools'
PACKAGE_NAME='xivo-dist_2016.02_all.deb'

MIRROR_KEY='http://mirror.xivo.solutions/xivo_current.key'
PROVD_URL='http://127.0.0.1:8666/provd/configure/plugin_server'

PROVD_CONFIG='/provd/config.py'

XIVO_CONFD_PORT=9486

function download_package() {
    wget ${PACKAGE_URL}/${PACKAGE_NAME} -O ${PACKAGE_NAME}
    wget ${MIRROR_KEY} -O - | apt-key add -
}

function install_package() {
    rm -f /etc/apt/sources.list.d/xivo.list
    dpkg -i ${PACKAGE_NAME}
}

function update_provd_url_put() {
    curl --noproxy 127.0.0.1 \
    --request PUT \
    -H "Content-Type: application/vnd.proformatique.provd+json" \
    -d '{"param":{"value":"'${PLUGIN_URL}'"}}' \
    ${PROVD_URL}
}

function update_dhcp(){
    if [[ $(xivo_version_installed) < '14.01' ]]; then
        sed -i 's/xivo.fr/xivo.solutions/' /etc/pf-xivo/dhcpd-update.conf
        sed -i 's/xivo.io/xivo.solutions/' /etc/pf-xivo/dhcpd-update.conf
    else
        sed -i 's/xivo.fr/xivo.solutions/' /etc/xivo/dhcpd-update.conf
        sed -i 's/xivo.io/xivo.solutions/' /etc/xivo/dhcpd-update.conf
        sed -i 's/xivo.io/xivo.solutions/' /etc/xivo/asterisk/xivo_fax.conf
    fi
    if [[ -e "/usr/sbin/dhcpd-update" ]]; then
        sed -i 's/xivo.fr/xivo.solutions/' /usr/sbin/dhcpd-update
        sed -i 's/xivo.io/xivo.solutions/' /usr/sbin/dhcpd-update
    fi
}

function update_provd_url_sed() {
    sed -i 's/xivo.io/xivo.solutions/' ${1}${PROVD_CONFIG}
}

function xivo_package() {
	list_packages_with_filter "?installed?name(\"^xivo$|^xivo-base$|^pf-xivo$\")" | head -n1
}

function xivo_version_installed() {
	echo "$(LANG='C' apt-cache policy $(xivo_package) | grep Installed | grep -oE '[0-9]{2}\.[0-9]+(\.[0-9]+)?|1\.2\.[0-9]{1,2}' | head -n1)"
}

function list_packages_with_filter () {
	filter="$1"
	aptitude -q -F '%p' --disable-columns search "$filter"
}

function is_xivo_configured() {
    if [ -f "/var/lib/xivo/configured" -o -f "/var/lib/pf-xivo/configured" -o -f "/var/lib/xivo-config/configured" \
        -o -f "/var/lib/pf-xivo-base-config/configured" ] ; then
        return 0
    elif [[ $(xivo_version_installed) > '14.16' ]]; then
        if [ ! -f "/var/run/xivo-confd/xivo-confd.pid" ] ; then
            echo "ERROR: xivo-confd is not running: cannot check if the web wizard has been run."
            exit 1
        fi
        [ -n "$(curl -skX GET --header 'Accept: application/json' "https://localhost:$XIVO_CONFD_PORT/1.1/wizard" | grep '\"configured\"[[:space:]]*:[[:space:]]*true')" ]
    else
        return 1
    fi
}

function get_python_dist_packages() {
    if [[ $(xivo_version_installed) < '13.25' ]]; then 
        PYPATH="/usr/lib/pymodules/python2.6/"
    else
        PYPATH=`python -c "from distutils.sysconfig import get_python_lib; import sys; sys.stdout.write(get_python_lib())";`
    fi
    echo ${PYPATH}
}

function check_wizard_has_been_run() {
	local xivo_package=$(xivo_package)
	if [[ $(xivo_version_installed) < '13.03' && -f "/etc/$xivo_package/web-interface/xivo.ini" ]]; then
		touch "/var/lib/$xivo_package/configured"
		chmod 664 "/var/lib/$xivo_package/configured"
	fi
	if ! is_xivo_configured; then
		echo "Wizard on this XiVO has not been run yet."
		local python_path=$(get_python_dist_packages)
		update_provd_url_sed ${python_path}
	else
	    echo "Wizard on this XiVO has already been run."
        if ps ax | grep -v grep | grep provd > /dev/null
        then
            echo "xivo-provd is running"
            update_provd_url_put
        else
            echo "xivo-provd is not running, please run it and re-run this script"
            exit 1
        fi
	fi
}

download_package
install_package
update_dhcp
check_wizard_has_been_run

echo "Your XiVO has been switched to xivo.solutions successfully."
echo "Votre XiVO a été basculé vers xivo.solutions avec succès."
