#!/bin/sh

add_litecoin_user() {
    # If the litecoin user does not exist, create it.
    if ! grep -q -E '^litecoin:' /etc/passwd; then
        echo "Could not find user 'litecoin' - creating user 'litecoin' with disabled password"
        adduser --gecos "" --disabled-password litecoin
    fi
}

rand_str() {
     echo $(cat /dev/urandom | tr -dc "0-9A-Fa-f" | head -c 30)
}

gen_litecoin_conf() {
    if [ ! -d "/home/litecoin/.litecoin" ]; then
        echo " >> Folder /home/litecoin/.litecoin does not exist. Creating it..."
        mkdir -p /home/litecoin/.litecoin
        chown litecoin:litecoin /home/litecoin/.litecoin
    fi
    if [ ! -f "/home/litecoin/.litecoin/litecoin.conf" ]; then
        echo " >> Generating basic default litecoin.conf into: /home/litecoin/.litecoin/litecoin.conf"
        cat > /home/litecoin/.litecoin/litecoin.conf <<EOF
rpcuser=litecoin
rpcpassword=$(rand_str)
rpcallowip=127.0.0.1
rpcallowip=::1
server=1
listen=1
daemon=1
logtimestamps=1
maxconnections=64

EOF
        chmod 700 /home/litecoin/.litecoin/litecoin.conf
        chown litecoin:litecoin /home/litecoin/.litecoin/litecoin.conf
    fi
}

if [ "$1" = "install" ]; then
    if [ "$#" -gt 1 ]; then
        # before the removed package is upgraded
        add_litecoin_user
        gen_litecoin_conf
    else
        # before the package is fresh(?) installed
        add_litecoin_user
        gen_litecoin_conf
    fi
elif [ "$1" = "upgrade" ]; then
    # 2 = old-version 3 = new-version
    # before the package is upgraded
    add_litecoin_user
#elif [ "$1" = "abort-upgrade" ]; then
    # If postrm fails during upgrade or fails on failed upgrade
fi

