#!/bin/bash -e
#-e Causes bash script to exit if any of the installers
#return with a non-zero return value.

if [[ $EUID -ne 0 ]]; then
    echo "Please run as root user."
    exit 1
fi


showhelp () {
    echo "Usage: airtime-install [options]
--help|-h                         Displays usage information.
--overwrite|-o                    Overwrite any existing config files.
--preserve|-p                     Keep any existing config files.
--no-db|-n                        Turn off database install.
--reinstall|-r                    Force a fresh install of this Airtime Version
--media-monitor|-m                Install only media-monitor
--pypo|-p                         Install only pypo and liquidsoap
--web|-w                          Install only files for web-server"
    exit 0
}

rabbitmq_install () {
    RABBITMQ_VHOST="/airtime"
    RABBITMQ_USER="airtime"
    RABBITMQ_PASSWORD=$(awk -F ' = ' '{if (! ($0 ~ /^;/) && $0 ~ /^password/ ) print $2}' /etc/airtime/airtime.conf)
    EXCHANGES="airtime-pypo|pypo-fetch|airtime-media-monitor|media-monitor"

    rabbitmqctl list_vhosts | grep $RABBITMQ_VHOST
    RESULT="$?"

    if [ $RESULT = "0" ]; then
        rabbitmqctl delete_vhost $RABBITMQ_VHOST
        rabbitmqctl delete_user $RABBITMQ_USER
    fi

    rabbitmqctl add_vhost $RABBITMQ_VHOST
    rabbitmqctl add_user $RABBITMQ_USER $RABBITMQ_PASSWORD
    rabbitmqctl set_permissions -p $RABBITMQ_VHOST $RABBITMQ_USER "$EXCHANGES" "$EXCHANGES" "$EXCHANGES"

    export RABBITMQ_USER
    export RABBITMQ_PASSWORD
    export RABBITMQ_VHOST
}

overwrite="f"
preserve="f"
nodb="f"
reinstall="f"
mediamonitor="f"
pypo="f"
showrecorder="f"
web="f"
disable_deb_check="f"

set -- $(getopt -l help,overwrite,preserve,no-db,reinstall,media-monitor,pypo,web,liquidsoap-keep-alive,disable-deb-check "hopnrmywld" "$@")
while [ $# -gt 0 ]
do
    case "$1" in
    (-h|--help) showhelp; exit 0;;
    (-o|--overwrite) overwrite="t";;
    (-p|--preserve) preserve="t";;
    (-n|--no-db) nodb="t";;
    (-r|--reinstall) reinstall="t";;
    (-m|--media-monitor) mediamonitor="t";;
    (-y|--pypo) pypo="t";;
    (-w|--web) web="t";;
    (-d|--disable-deb-check) disable_deb_check="t";;
    
    (--) shift; break;;
    (-*) echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
    (*)  break;;
    esac
    shift
done

if [ "$mediamonitor" = "f" -a "$pypo" = "f" -a "$web" = "f" ]; then
    #none of these install parameters were specified, so by default we install all of them
    mediamonitor="t"
    pypo="t"
    showrecorder="t"
    web="t"
fi

if [ "$disable_deb_check" == "f" ]; then
    set +e
    DEB=$(dpkg -s airtime 2> /dev/null | grep Status)
    set -e
    if [[ "$DEB" = "Status: install ok installed" ]]; then
        echo -e "\nDebian package of Airtime detected. Please use the debian package to upgrade.\n"
        exit 1
    fi
fi


#Update apt sources.list to point to the new deb-multimedia domain.
sed -i s/www.debian-multimedia.org/www.deb-multimedia.org/g /etc/apt/sources.list

# Absolute path to this script, e.g. /home/user/bin/foo.sh
SCRIPT=`readlink -f $0`
# Absolute path this script is in, thus /home/user/bin
SCRIPTPATH=`dirname $SCRIPT`
AIRTIMEROOT=$SCRIPTPATH/../

echo "* Making sure /etc/default/locale is set properly"
set +e
update-locale
cat /etc/default/locale | grep -i "LANG=.*UTF-\?8"
if [ "$?" != "0" ]; then
    echo -e " * Fail\n"
    echo "A non UTF-8 default locale found in /etc/default/locale. Airtime requires
a UTF-8 locale to run. To fix this please do the following:

Ubuntu:
Put line 'en_US.UTF-8 UTF-8' (or similar) without quotes to '/var/lib/locales/supported.d/local', 
replacing any existing lines.
A list of supported locales is available in '/usr/share/i18n/SUPPORTED'
Then run 'sudo dpkg-reconfigure locales'

Debian:
Run 'sudo dpkg-reconfigure locales' and use the interface to select 'en_US.UTF-8 UTF-8' (or similar).
On the second page select this new locale as the default.

After these changes have been made simply run install again.

Now exiting install...
"
    exit 1
fi
set -e

# Check if airtime exists already
set +e
php --php-ini ${SCRIPTPATH}/airtime-php.ini ${SCRIPTPATH}/include/airtime-installed-check.php
result=$?
set -e

DO_UPGRADE="0"
if [ "$result" -eq "0" ]; then
    echo " * None found."
    
    #Make sure any straggler config files are removed. Reason for this is that they may be from
    #an older version of Airtime, but since there no database installed, we have no idea how to 
    #handle these (what version are they from?). 
    rm -f "/etc/airtime/airtime.conf"
    rm -f "/etc/airtime/api_client.cfg"
    rm -f "/etc/airtime/liquidsoap.cfg"
    rm -f "/etc/airtime/media-monitor.cfg"
    rm -f "/etc/airtime/pypo.cfg"
elif [ "$result" -eq "1" -a "$reinstall" = "f" ]; then
    echo " * Same version of Airtime already installed! Reusing database."
    nodb='t'
    overwrite='f'
elif [ "$result" -eq "2" ]; then
    echo " * Previous version of Airtime already installed..will perform upgrade."
    DO_UPGRADE="1"
elif [ "$result" -eq "3" ]; then
    echo " * You require at least Airtime 1.8.0 installed for upgrade."
    exit 1
fi

#We don't want any of our python services running if we are doing an upgrade/reinstall.
#They will be automatically restarted later on.
echo "* Temporarily stopping any previous running services"
set +e
monit unmonitor airtime-media-monitor >/dev/null 2>&1
monit unmonitor airtime-liquidsoap >/dev/null 2>&1
monit unmonitor airtime-playout >/dev/null 2>&1
set -e
if [ -e /etc/init.d/airtime-media-monitor ]; then
    invoke-rc.d airtime-media-monitor stop > /dev/null 2>&1
fi
if [ -e /etc/init.d/airtime-playout ]; then
    invoke-rc.d airtime-playout stop > /dev/null 2>&1
fi
if [ -e /etc/init.d/airtime-liquidsoap ]; then
    invoke-rc.d airtime-liquidsoap stop > /dev/null 2>&1
fi

#export these variables to make them available in sub bash scripts
export DO_UPGRADE
export mediamonitor
export pypo
export showrecorder
export web
export reinstall
export nodb
export overwrite
export preserve

set +e
test "$mediamonitor" = "t" -o "$pypo" = "t"
export python_service=$?
set -e

echo -e "\n******************************** Install Begin *********************************"
rm -rf "/usr/lib/airtime"
mkdir -p /usr/lib/airtime

if [ "$python_service" -eq "0" ]; then
    $AIRTIMEROOT/python_apps/python-virtualenv/virtualenv-install.sh

    virtualenv_bin="/usr/lib/airtime/airtime_virtualenv/bin/"
    . ${virtualenv_bin}activate
    python $AIRTIMEROOT/python_apps/create-pypo-user.py
fi

if [ "$DO_UPGRADE" -eq "1" ]; then
    #do upgrade
    php --php-ini ${SCRIPTPATH}/airtime-php.ini ${SCRIPTPATH}/include/airtime-upgrade.php $@
fi

set +e
if [ "$DO_UPGRADE" -eq "0" ]; then 
    php --php-ini ${SCRIPTPATH}/airtime-php.ini ${SCRIPTPATH}/include/airtime-install.php $@
    result=$?

    if [ "$result" -ne "0" ]; then
        #There was an error, exit with error code.
        echo "There was an error during install. Exit code $result"
        exit 1
    fi
fi

rabbitmq_install
set -e


export airtime_service_start='t'
$SCRIPTPATH/include/airtime-copy-files.sh
$SCRIPTPATH/include/airtime-initialize.sh $@

if [ "$mediamonitor" = "t" -o "$pypo" = "t" ]; then
    #deactivate virtualenv
    deactivate
fi


#An attempt to force apache to realize that files are updated on upgrade...
touch /usr/share/airtime/public/index.php

if [ "$python_service" -eq "0" ]; then
    #only run airtime-check-system if all components were installed
    echo -e "\n*** Verifying your system environment, running airtime-check-system ***"
    sleep 10

    set +e
    airtime-check-system --no-color
    set -e
fi

echo -e "\n******************************* Install Complete *******************************"