#!/usr/bin/env bash

declare -i uid="$(id -u)"
if [[ $uid != 0 ]]
then
    echo 'Must be run by root user!' 1>&2
    exit 1
fi

# NB: must happen before get_scriptpath
unset CDPATH

# NB: can't put this in common.bash since finding
# common.bash depends on it
# http://www.ostricher.com/2014/10/the-right-way-to-get-the-directory-of-a-bash-script/
function get_scriptpath
{
    local sdir='unset'
    local target='unset'
    local bsrc="${BASH_SOURCE[0]}"
    while [[ -h $bsrc ]]
    do
        target="$(readlink $bsrc)"
        if [[ $target == /* ]]
        then
            bsrc="$target"
        else
            sdir="$(dirname $bsrc)"
            bsrc="$sdir/$target"
        fi
    done
    echo "$(cd -P $(dirname $bsrc) && pwd)"
}
declare -r script_path="$(get_scriptpath)"

source "$script_path/../lib/gen_riak_conf.bash"

opt_passed='false'
opt_install_riak='false'
opt_start_riak='false'
opt_download_url='unset'

while getopts "isd:" opt; do
    case $opt in
        d)
            opt_download_url="$OPTARG";;
        i)
            opt_passed='true'
            opt_install_riak='true';;
        s)
            opt_passed='true'
            opt_start_riak='true';;
    esac
done

if [[ $opt_passed == 'true' ]]
then
    declare -r install_riak="$opt_install_riak"
    declare -r start_riak="$opt_start_riak"
else
    declare -r install_riak='true'
    declare -r start_riak='false'
fi

if [[ $opt_download_url == 'unset' ]]
then
    declare -r download_url='https://packagecloud.io/install/repositories/basho/riak/script.deb.sh'
else
    declare -r download_url="$opt_download_url"
    declare -r dpkg_name="${download_url##*/}"
fi

if [[ $install_riak == 'true' ]]
then
    if [[ $download_url == *.deb.sh ]]
    then
        curl -s "$download_url" | bash
        apt-get install riak
    elif [[ $download_url == *.deb ]]
    then
        curl -O "$download_url"
        dpkg -i "$dpkg_name"
    else
        echo "Don't know how to install from $download_url, exiting!" 1>&2
        exit 1
    fi

    declare -r riak_conf=/etc/riak/riak.conf
    if [[ ! -f $riak_conf ]]
    then
        echo "Could not find $riak_conf file!" 1>&2
        exit 1
    fi

    gen_riak_conf "$riak_conf" 8098 8087
fi

if [[ $start_riak == 'true' ]]
then
    riak start
    riak-admin wait-for-service riak_kv
    riak-admin wait-for-service riak_pipe
    riak-admin wait-for-service yokozuna
fi

# NB: must exit 0 so we don't use the last exit val
exit 0
