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


LOGFILE="/var/log/xivouc_installer_$(date +'%Y%m%d_%H%M%S').log"

mkdir -p "$(dirname "$LOGFILE")"
exec > >(tee -a "$LOGFILE") 2>&1

XIVO_CONFD_PORT=9486
NON_INTERACTIVE=0

usage() {
    cat <<EOF
Usage: $0 [OPTIONS]

Options:
  -s            Run in non-interactive mode
  -h            Show this help message
EOF
}

while getopts ":sh" opt; do
    case "$opt" in
        s)
            NON_INTERACTIVE=1
            export DEBIAN_FRONTEND=noninteractive
            ;;
        h)
            usage
            exit 0
            ;;
        *)
            usage
            exit 1
            ;;
    esac
done

shift $((OPTIND - 1))

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."

if [ "$NON_INTERACTIVE" -eq 0 ]; then
    read -p "Are you sure you want to continue? (y/N): " -r
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo -e "\nAborting"
        exit 3
    fi
else
    echo "Running in non-interactive mode"
fi

apt-get update
apt-get install -y xivouc
