#! /bin/bash
MYNAME=$(basename $0)
MYDIR=$(dirname $0)
MYDIR=$(readlink -m "$MYDIR")
VERSION="0.0.16"
VERBOSE=""
LOGFILE=""

source $MYDIR/utilityfunctions.sh

#
# Prints the help text and exits.
#
function printHelpAndExit()
{
cat <<EOF
Usage:
  $MYNAME [OPTION]...

  $MYNAME - Installs a development environment to the local server. 

  -h, --help         Print this help and exit.
  -v, --version      Print version information and exit.
  --verbose          Print more messages.
  --log-file=FILE    Store all the messages in the given file too.
  
  --all              Check everything, install everything.
  --install-mongodb  Checks and installs the mongodb driver and mongo-c.
  --install-mariadb  Checks and installs the MariaDb library.
  --install-mysql    Installs the mysql server with root password.
  --install-postgre  Installs the postgresql stuff.
  --update-libssh    Installs the new version of the libssh package.
  --update-packages  Updates packages of the server.

  --no-containers    Do not install container virtualization technology.

EOF
    exit 0
}

ARGS=$(\
    getopt \
        -o hv \
        -l "help,verbose,version,log-file:,all,\
install-mongodb,install-mariadb,install-mysql,install-postgre,update-libssh,\
update-packages,no-containers" \
        -- "$@")

if [ $? -ne 0 ]; then
    exit 6
fi

eval set -- "$ARGS"
while true; do
    case "$1" in
        -h|--help)
            shift
            printHelpAndExit
            ;;

        --verbose)
            shift
            VERBOSE="true"
            ;;

        -v|--version)
            shift
            printVersionAndExit
            ;;

        --log-file)
            shift
            LOGFILE=$(readlink -m "$1")
            shift
            ;;

        --all)
            shift
            OPTION_ALL="true"
            ;;

        --install-mongodb)
            shift
            OPTION_INSTALL_MONGODB="true"
            ;;

        --install-mariadb)
            shift
            OPTION_INSTALL_MARIADB="true"
            ;;

        --install-mysql)
            shift
            OPTION_INSTALL_MYSQL="true"
            ;;

        --install-postgre)
            shift
            OPTION_INSTALL_POSTGRE="true"
            ;;

        --update-libssh)
            shift
            OPTION_UPDATE_LIBSSH="true"
            ;;

        --update-packages)
            shift
            OPTION_INSTALL_PACKAGES="true"
            ;;

        --no-containers)
            shift
            NO_CONTAINERS_OPTION="--no-containers"
            ;;

        --)
            shift
            break
            ;;

        *)
            ;;
    esac
done

function install_package() 
{
    local package
    local retcode=0
    local tempfile=$(mktemp)

    package="$1"

    printf "%-32s" "${package}"
    if dpkg -l | grep " $1 " > /dev/null 2>&1; then
        echo "[INSTALLED]"
    else
        echo "[INSTALLING]"
        sudo apt-get -y --force-yes install "$package" >>$tempfile 2>>$tempfile
        retcode=$?

        if [ "$retcode" != "0" ]; then
            cat "$tempfile"
        fi
    fi

    rm -f "$tempfile"
    return $retcode
}

function check_install_libssh_ppa()
{
    echo -ne "Checking for libssh 0.7.x ... "
    if dpkg -l | grep "libssh-4.*0.7" > /dev/null 2>&1; then
        echo "OK (0.7)" # installed
    elif dpkg -l | grep "libssh-4.*0.8" > /dev/null 2>&1; then
        echo "OK (0.8)" # installed
    else
        echo "Not installed, installing"
        sudo apt-get -y --force-yes install software-properties-common $1
        sudo apt-add-repository -y -u ppa:kedazo/libssh-0.7.x
        sudo apt-get -y -q update
        sudo apt-get -y --force-yes install libssh-dev libssh-4 libssh-dbg
    fi
}

function install_mysql_server()
{
    #
    # Installing mysql-server with a root password.
    #
    echo "mysql-server-5.5 mysql-server/root_password password p" |\
        sudo debconf-set-selections
    echo "mysql-server-5.5 mysql-server/root_password_again password p" |\
        sudo debconf-set-selections

    install_package mysql-server
}

function install_postgresql()
{
    if [ -f /opt/postgresql/include/libpq-fe.h ]; then
        echo "* (custom) postgresql is installed."
    elif [ -f /usr/include/postgresql/libpq-fe.h ]; then
        echo "* (system) postgresql is installed."
    else
        if ! [ -f postgresql-11.1.tar.bz2 ]; then
            echo "* downloading postgresql."
            wget --no-check-certificate \
            https://ftp.postgresql.org/pub/source/v11.1/postgresql-11.1.tar.bz2 \
            -O postgresql-11.1.tar.bz2 || exit $?
        fi
        echo "* installing postgresql."
        tar -xvjpf postgresql-11.1.tar.bz2 || exit $?

        pushd postgresql-11.1
        ./configure \
            --without-ldap \
            --without-bonjour \
            --without-gssapi \
            --without-perl \
            --without-python \
            --without-readline \
            --with-openssl \
            --without-pam \
            --prefix=/opt/postgresql || exit $?

        sudo mkdir -p /opt/postgresql || exit $?;
        sudo chown -R ${USER} /opt/postgresql || exit $?;
        make -j5 && sudo make -j5 install || exit $?
        popd
    fi    
}

#
# Installs basic packages that we might use during development. This is a pretty
# subjective list but proven to be handy.
#
function install_packages()
{
    pip-host-control --status="Installing packages..."
    if [ -z "$NO_CONTAINERS_OPTION" ]; then
        install_package lxc1
    fi

    install_package jq
    install_package tree
    install_package iotop
    install_package wget
    install_package git
    install_package autoconf
    install_package make
    install_package g++
    install_package flex
    install_package bison
    install_package pkgconf
    install_package libsqlite3-dev
    install_package libldap2-dev

    #install_package vagrant
    #install_package virtualbox
    install_mysql_server
}

#
# Install dependencies
#
function install_dependencies()
{
    pip-host-control --status="Installing dependencies..."

    install_package git
    install_package wget
    install_package xz-utils
    install_package make
    install_package g++
    install_package flex
    install_package bison
    install_package rpm
    install_package dpkg-dev
    install_package cmake
    install_package libssl-dev
    check_install_libssh_ppa

    # for mongodb
    install_package libboost-dev

    #check_install_dep libboost-all-dev
    install_package libboost-filesystem-dev
    install_package libboost-program-options-dev
    install_package libboost-regex-dev
    install_package libboost-system-dev
    install_package libboost-test-dev
    install_package libboost-thread-dev
    install_package scons
}


#
# Downloading clustercontrol source
#
function pull_clustercontrol_source()
{
    pushd "$HOME" >/dev/null 2>/dev/null 

    pip-host-control --status="Installing clustercontrol..."
    if [ -d "${PROJECT_CC_WORKER_DIR}" ]; then
        cd ${PROJECT_CC_WORKER_DIR}
        git pull
    else
        git clone git@github.com:severalnines/clustercontrol-enterprise.git
        cd "${PROJECT_CC_WORKER_DIR}"
        
        docs/ubuntu_compile.sh
        RETCODE=$?
        echo "+++ RETCODE: $RETCODE"

        if ! grep 'mysql-cluster-gpl-7.2' ~/.bashrc; then
            # FIXME: This should actually find the directory.
            echo 'export PATH=/opt/mysql-cluster-gpl-7.2.28-linux2.6-x86_64/bin:$PATH' \
            >> ~/.bashrc
            echo "Modified ~.bashrc"
        fi

    fi

    popd >/dev/null 2>/dev/null
}

function compile_clustercontrol()
{
    local source_dir="${PROJECT_CC_WORKER_DIR}"

    pip-host-control --status="Compiling clustercontrol..."
    
    if [ ! -d "$source_dir" ]; then
        echo "Directory '$source_dir' is not found."
        return 1
    fi

    pushd "$source_dir"
    ./autogen.sh
    make -j20
    popd 

    pushd "$source_dir/tests"
    ./autogen.sh
    make -j20
    popd 
}

function pull_s9s_source()
{
    pushd "$HOME" >/dev/null 2>/dev/null 

    pip-host-control --status="Installing s9s..."
    if [ -d "s9s-tools" ]; then
        cd s9s-tools
        git pull
    else
        git clone git@github.com:severalnines/s9s-tools.git
        #cd "s9s-tools"
    fi

    popd >/dev/null 2>/dev/null
}

function compile_s9s()
{
    local source_dir="$HOME/s9s-tools"

    pip-host-control --status="Compiling s9s..."
    
    if [ ! -d "$source_dir" ]; then
        echo "Directory '$source_dir' is not found."
        return 1
    fi

    pushd "$source_dir"
    ./autogen.sh
    make -j20
    popd 
}


function install_mongodb()
{
    tmp_dir="/var/tmp/pip_install_dev_mongodb_$$"

    if grep -q 'MONGO_SASL 1' /opt/mongo/include/mongo/config.h; then
        echo "The mongodb-driver (with sasl) is already installed."
        return 0
    fi

    #
    #
    #
    mkdir -p "$tmp_dir"
    if [ ! -d "$tmp_dir" ]; then
        echo "Failed to create directory '$tmp_dir'."
        return 1
    fi

    echo "Entering directory '$tmp_dir'..."
    pushd "$tmp_dir" >/dev/null 2>/dev/null
    if [ $? -ne 0 ]; then
        echo "Failed to enter directory"
        return 1
    fi

    #
    #
    #
#
# MongoC
#
if [ ! -f /opt/mongo-c/include/libmongoc-1.0/mongoc.h ]; then
    if ! [ -f cyrus-sasl-2.1.27.tar.gz ]; then
        echo "* downloading the SASL library for MongoDb."
        wget https://github.com/cyrusimap/cyrus-sasl/releases/download/cyrus-sasl-2.1.27/cyrus-sasl-2.1.27.tar.gz || exit $?
    fi

    echo "* installing the SASL library for MongoDb."
    tar -xzpf cyrus-sasl-2.1.27.tar.gz || exit $?
    pushd cyrus-sasl-2.1.27
    CFLAGS="-fPIC" ./configure --with-pic --enable-scram --disable-gssapi --enable-static=yes --prefix=/opt/cyrus-sasl || exit $?
    make -j3 || exit $?
    sudo make -j3 install || exit $?
    popd

    if [ ! -f mongo-c-driver-1.13.0.tar.gz ]; then
        wget 'https://github.com/mongodb/mongo-c-driver/releases/download/1.13.0/mongo-c-driver-1.13.0.tar.gz' || exit $?
    fi
    echo "* installing the new MongoC driver"
    tar -xzpf mongo-c-driver-1.13.0.tar.gz || exit $?
    pushd mongo-c-driver-1.13.0
    cmake -DCMAKE_PREFIX_PATH=/opt/ssl102p/ -DCMAKE_PREFIX_PATH=/opt/cyrus-sasl/ -DCMAKE_INSTALL_PREFIX:PATH=/opt/mongo-c -DMONGOC_ENABLE_ICU=OFF -DENABLE_ICU=OFF
    make -j3 || exit $?
    sudo make -j3 install
    popd
fi
}

function install_mongoc()
{
    local tmp_dir="/var/tmp/pip_install_dev_mongoc_$$"

    if [ -f /opt/mongo-c/include/libmongoc-1.0/mongoc.h ]; then
        echo "The mongo-c is already installed."
        return 0
    fi

    #
    #
    #
    mkdir -p "$tmp_dir"
    if [ ! -d "$tmp_dir" ]; then
        echo "Failed to create directory '$tmp_dir'."
        return 1
    fi

    echo "Entering directory '$tmp_dir'..."
    pushd "$tmp_dir" >/dev/null 2>/dev/null
    if [ $? -ne 0 ]; then
        echo "Failed to enter directory"
        return 1
    fi

    if [ ! -f mongo-c-driver-1.12.0.tar.gz ]; then
        wget 'https://github.com/mongodb/mongo-c-driver/releases/download/1.12.0/mongo-c-driver-1.12.0.tar.gz' || exit $?
    fi

    echo "* installing the new MongoC driver"
    tar -xzpf mongo-c-driver-1.12.0.tar.gz || exit $?
    
    pushd mongo-c-driver-1.12.0
    cmake -DCMAKE_INSTALL_PREFIX:PATH=/opt/mongo-c -DMONGOC_ENABLE_ICU=OFF
    make -j3 || exit $?
    sudo make -j3 install
    popd

    #
    #
    #
    popd
    rm -rvf "$tmp_dir"
}

function install_mariadb()
{
    #
    # MariaDB library (LGPL)
    # https://downloads.mariadb.com/Connectors/c/connector-c-3.0.8/
    #
    MDBPATH="/opt/mariadb-connector-c-3.0.8-linux-x86_64"
    MDBURL="https://downloads.mariadb.com/Connectors/c/connector-c-3.0.8/mariadb-connector-c-3.0.8-linux-x86_64.tar.gz"
    MDBFILE=$(basename ${MDBURL})

    ORIGIFS=$IFS
    IFS='
    '
    DIRS=`find /opt/mariadb-connector-c-* -name mariadb_config`
    for DIR in $DIRS; do
        MDBPATH=`dirname $(dirname $DIR)`
        echo "* Using existing MariaDB C Connector installation: $DIR"
    done
    IFS=$ORIGIFS

    if [ -x ${MDBPATH}/bin/mariadb_config ]; then
       echo "* MariaDB C Connector is installed."
    else
        if [ ! -f ${MDBFILE} ]; then
            echo "* downloading MariaDB C Connector."
            wget ${MDBURL} -O ${MDBFILE} || exit $?
        fi

        # extract it
        echo "Extracting ${MDBFILE}"
        sudo tar -xzpf ${MDBFILE} -C /opt || exit $?
        echo "Changing permission in ${MDBPATH}"
        echo " - for directories"
        sudo find "${MDBPATH}" -type d -print0 | while read -d $'\0' file; do sudo chmod og+rx "$file" || exit $?; done
        echo " - for regular files"
        sudo find "${MDBPATH}" -type f -print0 | while read -d $'\0' file; do sudo chmod og+r "$file" || exit $?; done
        echo " - for executables"
        sudo find "${MDBPATH}" -type f -perm /111 -print0 | while read -d $'\0' file; do sudo chmod og+rx "$file" || exit $?; done
        echo "Permissions ok"
    fi

    export PATH=${MDBPATH}/bin:${PATH}
    echo "${MDBPATH}/bin:"

    pushd /opt
    sudo ln -s mariadb-connector-c-3.0.8-linux-x86_64 mariadb-connector
    popd
}

function update_packages()
{
    local tmp

    sudo apt update
    sudo apt -y --force-yes upgrade
    sudo apt -y --force-yes autoremove

    tmp=$(which purge-old-kernels)
    if [ -z "$tmp" ]; then
        sudo apt -y --force-yes install byobu
    fi

    sudo purge-old-kernels
}


if [ -n "$OPTION_INSTALL_MYSQL" ]; then
    install_mysql_server
    exit $?
fi

if [ -n "$OPTION_UPDATE_LIBSSH" ]; then
    check_install_libssh_ppa
    exit $?
fi

if [ -n "$OPTION_INSTALL_PACKAGES" ]; then
    update_packages
fi



if [ -n "$OPTION_ALL" ]; then
    install_packages
    [ $? -ne 0 ] && exit 1
    
    install_dependencies
    [ $? -ne 0 ] && exit 1
    
    install_mongodb
    [ $? -ne 0 ] && exit 1
    
    install_mongoc
    [ $? -ne 0 ] && exit 1

    pull_clustercontrol_source
    compile_clustercontrol 

    pull_s9s_source
    compile_s9s
elif [ -n "$OPTION_INSTALL_MONGODB" ]; then
    install_mongodb
    [ $? -ne 0 ] && exit 1
    
    install_mongoc
    [ $? -ne 0 ] && exit 1
elif [ -n "$OPTION_INSTALL_MARIADB" ]; then
    install_mariadb
    [ $? -ne 0 ] && exit 1
elif [ -n "$OPTION_INSTALL_POSTGRE" ]; then
    install_postgresql
    [ $? -ne 0 ] && exit 1
else
    echo "Nothing to do, no command line option is provided with tasks."
fi

pip-host-control --status="Idle"

