#!/bin/sh

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

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

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

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

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

