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

SCRIPT_DIR="$( cd "$( dirname "$0" )" && pwd )"
AIRTIMEROOT="$( cd "$( dirname ${SCRIPT_DIR} )" && pwd )"

showhelp () {
    echo "Usage: sudo bash install [options]
    -h, --help, -?
                Display usage information
    -V, --version
                Display version information
    -v, --verbose
                More output
    -q, --quiet, --silent
                No output except errors
    -f, --force
                Turn off interactive prompts
    -d, --install-dependencies
                Install binary dependencies
    -w, --web-user=WEB_USER
                Set the default apache web user
    -r, --web-root=WEB_ROOT
                Set the web root for Airtime files
                This will copy the Airtime application files and make them
                accessible to the web user
                If no directory or an empty string is given, this defaults to
                an in-place installation, and will give the web user
                permissions on the current Airtime root
    -I, --in-place
                Set the current Airtime root as the working directory for
                Airtime
                Note that you will need to give your web user permissions on
                these directories
    -p, --postgres
                Create a default postgres user named 'airtime' with password
                'airtime'
    -a, --apache
                Install apache and deploy a basic configuration for Airtime
    -i, --icecast
                Install Icecast 2 and deploy a basic configuration for Airtime"
    exit 0
}

showversion () {
    . ${AIRTIMEROOT}/VERSION > /dev/null
    echo "Airtime Version ${PRODUCT_RELEASE}"
    exit 0
}

web_user="www-data"
web_root=""
in_place="f"
postgres="f"
apache="f"
icecast="f"
install_dependencies="f"
# Interactive
_i=1
# Verbose
_v=0
# Quiet
_q=0

function verbose() {
    if [[ ${_v} -eq 1 ]]; then
        echo -e "$@"
    fi
}

function loud() {
    if [[ ${_q} -eq 0 ]]; then
        echo -e "$@"
    fi
}

# Evaluate commands silently if quiet
function loudCmd() {
    if [[ ${_q} -eq 0 ]]; then
        eval $@
    else
        eval $@ > /dev/null
    fi
}

while :; do
    case "$1" in
        --help)
            showhelp
            ;;
        --version)
            showversion
            ;;
        --verbose)
            _v=1
            ;;
        --quiet|--silent)
            _q=1
            ;;
        --force)
            _i=0
            ;;
        --install-dependencies)
            install_dependencies="t"
            ;;
        --apache)
            apache="t"
            ;;
        --icecast)
            icecast="t"
            ;;
        --postgres)
            postgres="t"
            ;;
        --in-place)
            in_place="t"
            ;;
        --web-user)
            if [ "$2" ]; then
                web_user=$2
                shift 2
                continue
            else
                echo 'ERROR: Must specify a non-empty "--web-user WEB_USER" argument.' >&2
                exit 1
            fi
            ;;
        --web-user=?*)
            web_user=${1#*=} # Delete everything up to "=" and assign the remainder.
            ;;
        --web-user=)
            echo 'ERROR: Must specify a non-empty "--web-user=WEB_USER" argument.' >&2
            exit 1
            ;;
        --web-root)
            if [ "$2" ]; then
                web_root=$(readlink -f $2)
                shift 2
                continue
            else
                echo 'ERROR: Must specify a non-empty "--web-root WEB_ROOT" argument.' >&2
                exit 1
            fi
            ;;
        --web-root=?*)
            web_root=${1#*=} # Delete everything up to "=" and assign the remainder.
            ;;
        --web-root=)
            echo 'ERROR: Must specify a non-empty "--web-root=WEB_ROOT" argument.' >&2
            exit 1
            ;;
        --)
            shift
            break
            ;;
        -?*)
            for ((i = 1; i < ${#1}; i++)); do
                case "${1:$i:1}" in
                    h|\?)
                        showhelp
                        ;;
                    V)
                        showversion
                        ;;
                    v)
                        _v=1
                        ;;
                    q)
                        _q=1
                        ;;
                    f)
                        _i=0
                        ;;
                    d)
                        install_dependencies="t"
                        ;;
                    a)
                        apache="t"
                        ;;
                    i)
                        icecast="t"
                        ;;
                    p)
                        postgres="t"
                        ;;
                    I)
                        in_place="t"
                        ;;
                    w)
                        if [ "$2" ]; then
                            web_user=$2
                            continue
                        else
                            echo 'ERROR: Must specify a non-empty "-w WEB_USER" argument.' >&2
                            exit 1
                        fi
                        ;;
                    r)
                        if [ "$2" ]; then
                            web_root=$(readlink -f $2)
                            continue
                        else
                            echo 'ERROR: Must specify a non-empty "-d WEB_ROOT" argument.' >&2
                            exit 1
                        fi
                        ;;
                    *)
                        echo "$0: error - unrecognized option '${1:$i:1}'" >&2;
                        echo "Try 'install --help' for more information."
                        exit 1
                esac
            done
            ;;
        *)
            break
    esac
    shift
done

if [ -z web_root -a ! -d web_root ]; then
    echo "$web_root doesn't exist!"
    exit 1
fi

dist=`lsb_release -is`
code=`lsb_release -cs`

echo -e "\n   _____  .________________________.___   _____  ___________   "
echo    "  /  _  \ |   \______   \__    ___/|   | /     \ \_   _____/     "
echo    " /  /_\  \|   ||       _/ |    |   |   |/  \ /  \ |    __)_      "
echo    "/    |    \   ||    |   \ |    |   |   /    Y    \|        \     "
echo    "\____|__  /___||____|_  / |____|   |___\____|__  /_______  /     "
echo -e "        \/            \/                       \/        \/    \n"

if [ "$apache" = "f" -a ${_i} -eq 1 ]; then
    echo -e "Install default Airtime apache configuration? (Y/n): \c"
    read IN
    if [ "$IN" = "y" -o "$IN" = "Y" ]; then
        apache="t"
    fi
fi

if [ "$in_place" = "t" ]; then
    verbose "\n * Setting current Airtime directory as web root..."
    web_root=${AIRTIMEROOT}/airtime_mvc/public
    chmod -R 755 ${AIRTIMEROOT}
elif [ -n "$web_root" ]; then
    verbose "\n * Creating Apache web root directory..."
    mkdir -p ${web_root}/airtime/public/
    cp -R ${AIRTIMEROOT}/airtime_mvc/* ${web_root}/airtime/
    chmod -R 755 ${web_root}
else
    verbose "\n * Creating default Apache web root directory /usr/share/airtime/..."
    web_root="/usr/share"
    mkdir -p ${web_root}/airtime/public/
    cp -R ${AIRTIMEROOT}/airtime_mvc/* ${web_root}/airtime/
fi

if [ "$apache" = "t" ]; then
    loud "\n-----------------------------------------------------"
    loud "                * Installing Apache *                "
    loud "-----------------------------------------------------"

    loudCmd "apt-get -y --force-yes install apache2 libapache2-mod-php5"
    set +e
    apache2 -v | grep "2\.4" > /dev/null
    apacheversion=$?
    set -e

    if [ "$apacheversion" != "1" ]; then
        airtimeconfigfile="airtime.conf"
    else
        airtimeconfigfile="airtime"
    fi

    if [ ! -f /etc/apache2/sites-available/${airtimeconfigfile} ]; then
        verbose "\n * Creating Apache config for Airtime..."
        sed -e "s@WEB_ROOT@${web_root}@g" ${SCRIPT_DIR}/apache/airtime-vhost > /etc/apache2/sites-available/${airtimeconfigfile}
        loudCmd "a2dissite 000-default"
        loudCmd "a2ensite airtime"
    else
        verbose "\nApache config for Airtime already exists, skipping"
    fi
fi

if [ "$icecast" = "f" -a ${_i} -eq 1 ]; then
    echo -e "Install default Airtime Icecast configuration? (Y/n): \c"
    read IN
    if [ "$IN" = "y" -o "$IN" = "Y" ]; then
        icecast="t"
    fi
fi

if [ "$icecast" = "t" ]; then
    loud "\n-----------------------------------------------------"
    loud "               * Installing Icecast *                "
    loud "-----------------------------------------------------"
    
    loudCmd "DEBIAN_FRONTEND=noninteractive apt-get -y --force-yes install icecast2"

    verbose "\n * Enabling Icecast 2..."
    sed -i 's/ENABLE=false/ENABLE=true/g' /etc/default/icecast2
    set +e
    service icecast2 start
    set -e
fi

loud "\n-----------------------------------------------------"
loud "          * Installing Airtime Services *            "
loud "-----------------------------------------------------"

verbose "\n * Installing necessary binaries..."
loudCmd "apt-get -y --force-yes install liquidsoap python python-pip"
loudCmd "pip install setuptools"
verbose "...Done"

verbose "\n * Creating /usr/lib/airtime..."
mkdir -p /usr/lib/airtime
verbose "...Done"

verbose "\n * Creating /run/airtime..."
mkdir -p /run/airtime
chmod 755 /run/airtime
chown -R ${web_user}:${web_user} /run/airtime
verbose "...Done"

verbose "\n * Copying logging files..."
cp -R ${AIRTIMEROOT}/python_apps/std_err_override /usr/lib/airtime/std_err_override
verbose "...Done"

verbose "\n * Copying API client files..."
cp -R ${AIRTIMEROOT}/python_apps/api_clients /usr/lib/airtime/api_clients
verbose "...Done"

verbose "\n * Copying media-monitor files..."
cp -R ${AIRTIMEROOT}/python_apps/media-monitor/media-monitor /usr/lib/airtime/media-monitor
cp -R ${AIRTIMEROOT}/python_apps/media-monitor/media-monitor2 /usr/lib/airtime/media-monitor/mm2
verbose "...Done"

verbose "\n * Installing media-monitor..."
if [ -z web_root ]; then
    python ${web_root}/python_apps/media-monitor/setup.py install
elif [ "$in_place" = "t" ]; then
    python ${AIRTIMEROOT}/python_apps/media-monitor/setup.py install
else
    python /usr/share/airtime/python_apps/media-monitor/setup.py install
fi
verbose "...Done"

verbose "\n * Copying pypo files..."
mkdir -p /usr/lib/airtime/pypo
cp -R ${AIRTIMEROOT}/python_apps/pypo/pypo /usr/lib/airtime/pypo/bin/
verbose "...Done"

verbose "\n * Installing pypo..."
if [ -z web_root ]; then
    python ${web_root}/python_apps/pypo/setup.py install
elif [ "$in_place" = "t" ]; then
    python ${AIRTIMEROOT}/python_apps/pypo/setup.py install
else
    python /usr/share/airtime/python_apps/pypo/setup.py install
fi
verbose "...Done"

verbose "\n * Creating liquidsoap symlink..."
ln -sf /usr/bin/liquidsoap /usr/bin/airtime-liquidsoap
verbose "...Done"

sed "s@WEB_USER@${web_user}@g" ${SCRIPT_DIR}/lib/airtime-session-init-setup.conf > /etc/init/airtime-session-init-setup.conf
cp ${SCRIPT_DIR}/lib/airtime-session-init.conf /etc/init/airtime-session-init.conf
chmod 644 /usr/share/upstart/sessions/airtime*

initctl reload-configuration
service airtime-session-init-setup start

if [ ! -d /var/log/airtime ]; then
    loud "\n-----------------------------------------------------"
    loud "              * Installing Log Files *               "
    loud "-----------------------------------------------------"

    verbose "\n * Creating /var/log/airtime..."
    mkdir -p /var/log/airtime
    mkdir -p /var/log/airtime/media-monitor
    mkdir -p /var/log/airtime/pypo
    mkdir -p /var/log/airtime/pypo-liquidsoap
    
    verbose "\n * Creating /var/tmp/airtime..."
    mkdir -p /var/tmp/airtime/media-monitor
    mkdir -p /var/tmp/airtime/pypo/cache/
    mkdir -p /var/tmp/airtime/pypo/files/
    mkdir -p /var/tmp/airtime/pypo/tmp/
    mkdir -p /var/tmp/airtime/show-recorder/

    verbose "\n * Setting permissions on /var/log/airtime..."
    chmod -R a+x /var/log/airtime
    chown -R ${web_user}:${web_user} /var/log/airtime/
    
    verbose "\n * Setting permissions on /var/tmp/airtime..."
    chmod -R a+x /var/tmp/airtime
    chmod 755 /usr/lib/airtime/pypo/bin/liquidsoap_scripts/notify.sh
    chown -R ${web_user}:${web_user} /var/tmp/airtime/
    chown -R ${web_user}:${web_user} /usr/lib/airtime/

    verbose "\n * Copying logrotate files..."
    cp ${AIRTIMEROOT}/airtime_mvc/build/airtime-php.logrotate /etc/logrotate.d/airtime-php
    cp /usr/lib/airtime/pypo/bin/liquidsoap_scripts/airtime-liquidsoap.logrotate /etc/logrotate.d/airtime-liquidsoap
fi

loud "\n-----------------------------------------------------"
loud "                 * Installing PHP *                  "
loud "-----------------------------------------------------"

loudCmd "apt-get -y --force-yes install php5"

verbose "\n * Installing Zend framework..."
#Debian Squeeze only has zendframework package. Newer versions of Ubuntu have zend-framework package.
#Ubuntu Lucid has both zendframework and zend-framework. Difference appears to be that zendframework is for
#1.10 and zend-framework is 1.11
if [ "$dist" = "Debian" ]; then
    loudCmd "apt-get -y --force-yes install zendframework"
else
    loudCmd "apt-get -y --force-yes install libzend-framework-php"
fi

# PHP Config File for Apache
if [ ! -f "/etc/php5/apache2/conf.d/airtime.ini" ]; then
    verbose "\n * Creating Airtime PHP config for Apache..."
    cp ${SCRIPT_DIR}/php/airtime.ini /etc/php5/apache2/conf.d/airtime.ini
else
    verbose "\nAirtime PHP config for Apache already exists, skipping"
fi

# Enable modules
loudCmd "a2enmod rewrite php5"

loud "\n-----------------------------------------------------"
loud "              * Installing PostgreSQL *              "
loud "-----------------------------------------------------"

loudCmd "apt-get -y --force-yes install postgresql php5-pgsql"

setupAirtimePostgresUser() {
    # here-doc to execute this block as postgres user
    su postgres <<'EOF'
    set +e
    psql -d postgres -tAc "CREATE USER airtime WITH ENCRYPTED PASSWORD 'airtime'; ALTER USER airtime CREATEDB;"
    set -e
# don't indent this!
EOF
}

if [ "$postgres" = "t" ]; then
    setupAirtimePostgresUser
elif [ ${_i} -eq 1 ]; then
    echo -e "Create default airtime postgres user? (Y/n): \c"
    read IN
    if [ "$IN" = "y" -o "$IN" = "Y" ]; then
        setupAirtimePostgresUser
    fi
fi

loud "\n-----------------------------------------------------"
loud "               * Installing RabbitMQ *               "
loud "-----------------------------------------------------"

loudCmd "apt-get -y --force-yes install rabbitmq-server"

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

# Ignore errors in this check to avoid dying when vhost isn't found
set +e
rabbitmqctl list_vhosts | grep -w ${RABBITMQ_VHOST} > /dev/null
RESULT="$?"
set -e

# Only run these if the vhost doesn't exist
if [ "$RESULT" != "0" ]; then
    verbose "\n * Creating RabbitMQ user ${RABBITMQ_USER}..."

    rabbitmqctl add_vhost ${RABBITMQ_VHOST}
    rabbitmqctl add_user ${RABBITMQ_USER} ${RABBITMQ_PASSWORD}
else
    verbose "\nRabbitMQ user already exists, skipping creation"
fi

verbose "\n * Setting RabbitMQ user permissions..."
loudCmd "rabbitmqctl set_permissions -p ${RABBITMQ_VHOST} ${RABBITMQ_USER} \"$EXCHANGES\" \"$EXCHANGES\" \"$EXCHANGES\""

if [ ! -d "/etc/airtime" ]; then
    loud "\n-----------------------------------------------------"
    loud "                * Installing Airtime *               "
    loud "-----------------------------------------------------"

    verbose "\n * Creating /etc/airtime/ directory..."
    mkdir /etc/airtime
    chown -R ${web_user}:${web_user} /etc/airtime
fi

if [ ! -d "/srv/airtime" ]; then
    mkdir -p /srv/airtime
    chown -R ${web_user}:${web_user} /srv/airtime
fi

if [ "$install_dependencies" = "f" -a ${_i} -eq 1 ]; then
    echo -e "Install external binary dependencies? (Y/n): \c"
    read IN
    if [ "$IN" = "y" -o "$IN" = "Y" ]; then
        install_dependencies="t"
    fi
fi

if [ "$install_dependencies" = "t" ]; then
    loud "\n-----------------------------------------------------"
    loud "         * Installing External Dependencies *        "
    loud "-----------------------------------------------------"

    verbose "\n * Reading requirements-${dist,,}-${code,,}.apt..."
    loudCmd "apt-get -y -m --force-yes install $(grep -vE '^\s*#' ${SCRIPT_DIR}/lib/requirements-${dist,,}-${code,,}.apt | tr '\n' ' ')"
fi

verbose "\n * Restarting apache..."
loudCmd "service apache2 restart 2>/dev/null"

echo -e "\n-----------------------------------------------------"
echo    "                * Basic Setup DONE! *                "
echo    "                                                     "
echo    "  To get started with Airtime, visit localhost:5000  "
echo    "   or, if you've set up your own web configuration,  "
echo    "        the Airtime webroot on your webserver        "
echo    "            in your web browser of choice            "
echo    "-----------------------------------------------------"