#!/usr/bin/env bash

# Copyright (C) 2016 Avencall
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

set -e

XIVO_CONFD_PORT=9486

check_xivo_configured() {
    if [ ! -f "/var/run/xivo-confd/xivo-confd.pid" ] ; then
        echo "xivo-confd is not running: cannot check if the web wizard has been run."
        echo "Please run xivo-confd before installing XiVO UC."
        exit 1
    elif [ -z "$(curl -skX GET --header 'Accept: application/json' "https://localhost:$XIVO_CONFD_PORT/1.1/wizard" \
            | grep '\"configured\"[[:space:]]*:[[:space:]]*true')" ] ; then
        echo "Wizard on this XiVO has not been run yet."
        exit 2
    fi
}

check_xivo_configured
echo "XiVO UC will be installed."
read -p "Are you sure you want to continue? (y/N): " -r

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "\nAborting"
    exit 3
fi

apt-get install xivouc
