#!/bin/bash

set -e

DEBIAN_PKGS="mongodb python3.5 python3-pip python3-grib \
python3-bson python3-pymongo python3-serial \
python3-pymongo-ext python3-bson-ext python3-dev \
nodejs enchant nginx-full virtualenv \
gdal-bin python-gdal"

if [ ${1^^} == "-Y" ]
then
  AUTO=1
else
  AUTO=0
fi


# Check if root
if [ "$EUID" -ne 0 ]
then
    echo "You need root privileges to install Isomer. Use su or sudo."
    echo
    echo "If you want to install in development mode, please read:"
    echo "https://isomer.readthedocs.io/en/latest/dev/environment.html"
    exit
fi

echo "If you run into any trouble, please read the documentation at"
echo -e "\nhttps://isomer.readthedocs.io/en/latest/start/index.html\n"

# Find our package manager
if VERB="$( which apt-get )" 2> /dev/null; then
    echo "Proceeding with autodetected Debian based installation. Please be patient."

    if [ -n $AUTO ]
    then
        echo -e "\nAbout to update apt and install Debian packages: $DEBIAN_PKGS"
        echo -n "Ok? [Y/N] "
        read confirmation

        if [ ! ${confirmation^^} == 'Y' ]
        then
            exit
        fi
        echo "Installing"
    fi

    if [ ! -f /etc/apt/sources.list.d/nodesource.list ]
    then
        echo "Adding node source Debian repository."
        apt-get install -y apt-transport-https &>> output.log
        echo "deb https://deb.nodesource.com/node_7.x jessie main deb-src https://deb.nodesource.com/node_7.x jessie main" > /etc/apt/sources.list.d/nodesource.list
        wget -qO- https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -
        apt-get update &>> output.log
    fi

    apt-get install -y $DEBIAN_PKGS &>> output.log

    # This one doesn't run nicely, so we get it via pip:
    apt-get remove -y python3-crypto python3-cffi-backend &>> output.log

    npm install -g npm@4.2.0 &>> output.log

    git submodule init &>> output.log
    git submodule update &>> output.log

    virtualenv -p /usr/bin/python3.5 --system-site-packages venv &>> output.log
    source venv/bin/activate &>> output.log
    pip install -Ur requirements-dev.txt &>> output.log
    python setup.py develop &>> output.log

    systemctl start mongodb.service &>> output.log

    venv/bin/python iso install all &>> output.log
    venv/bin/python iso install frontend &>> output.log

    echo "All Done! Visit your new Installation by opening a browser and surfing to:"
    echo
    echo "https://localhost"

elif VERB="$( which yum )" 2> /dev/null; then
    echo "Modern Red Hat-based - NOT SUPPORTED YET"
elif VERB="$( which portage )" 2> /dev/null; then
    echo "Gentoo-based - NOT SUPPORTED YET"
elif VERB="$( which pacman )" 2> /dev/null; then
    echo "Arch-based - NOT SUPPORTED YET"
else
    echo "Your distribution is not yet supported." >&2
    exit 1
fi


