#!/bin/bash

# check root
if [ ! "$(id -u)" == "0" ]; then
    echo "must be root to run install script"
    exit 1
fi


# source directory
source_dir=$(cd "$(dirname "${BASH_SOURCE[0]}" )"; pwd)


electrum_config="/etc/electrum.conf"
function read_config()
{
    text=$1
    echo `grep -e ^$text $electrum_config |awk -F\= '{print $2}' | tail -n 1| tr -d ' '`
}
function write_config()
{
    sed -i -s "s#$1 =.*#$1 = $2#" $electrum_config
}

# create config file
if [ ! -f $electrum_config ]; then
    echo "Creating config file"
    cp $source_dir"/electrum.conf.sample" $electrum_config
fi


# read username
user=$(read_config "username")
if ! [ "$user" ]; then
    read -p "username for running daemon (default: electrum) " -r
    if [ $REPLY ]; then
	user=$REPLY
    else
	user="electrum"
    fi 
    write_config "username" $user
fi


# create user
if [ ! id -u $user >/dev/null 2>&1 ]; then
    echo "adding user $user"
    useradd $user
    echo "$user hard nofile 65536" >> /etc/security/limits.conf
    echo "$user soft nofile 65536" >> /etc/security/limits.conf
fi


# read path from config
default_path="/var/electrum-server"
path=$(read_config "path")
if ! [ "$path" ]; then
    read -p "Path for database (default: $default_path) " -r
    if [ $REPLY ]; then
	path=$REPLY
    else
	path=$default_path
    fi 
    write_config "path" $default_path
fi

# read path from config
default_logfile="/var/log/electrum.log"
logfile=$(read_config "logfile")
if ! [ "$logfile" ]; then
    read -p "Path of logfile (default: $default_logfile) " -r
    if [ $REPLY ]; then
	logfile=$REPLY
    else
	logfile=$default_logfile
    fi 
    write_config "logfile" $default_logfile
fi


# remove directory if it exists and is empty
if [ -d $path ]; then
    rmdir $path --ignore-fail-on-non-empty
fi


# download database
if [ ! -d $path ]; then
    echo "Database not found in $path."
    read -p "Do you want to download it from the Electrum foundry to $path ? " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
	mkdir -p $path
	wget -O - "http://reddwallet.org/electrum.tar.gz" | tar --extract --gunzip --strip-components 1 --directory $path --file -
    fi
fi

# set owner
chown -R $user:$user $path


# create log file
logfile=$(read_config "logfile")
if ! [ -f $logfile ]; then
    touch $logfile
    chown $user:$user $logfile
fi


reddcoind_user=$(read_config "user")
if ! [ "$reddcoind_user" ]; then
    read -p "rpcuser (from your reddcoin.conf file): " -r
    write_config "user" $REPLY
fi

reddcoind_password=$(read_config "password")
if ! [ "$reddcoind_password" ]; then
    read -p "rpcpassword (from your reddcoin.conf file): " -r
    write_config "password" $REPLY
fi


# finish
echo "Configuration written to $electrum_config."
echo "Please edit this file to finish the configuration."
echo "If you have not done so, please run 'python setup.py install'"
echo "Then, run 'electrum-server' to start the daemon"
