#!/bin/sh

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

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

C_DATADIR="/home/monero/.bitmonero"
C_CONF="${C_DATADIR}/bitmonero.conf"
C_WALCONF="${C_DATADIR}/wallet.conf"

gen_monero_conf() {
    if [ ! -d "$C_DATADIR" ]; then
        echo " >> Folder $C_DATADIR does not exist. Creating it..."
        mkdir -p "${C_DATADIR}/logs"
        chown monero:monero "$C_DATADIR" "${C_DATADIR}/logs"
    fi
    if [ ! -f "$C_CONF" ]; then
        echo " >> Generating basic default bitmonero.conf into: $C_CONF"
        cat > "$C_CONF" <<EOF
data-dir=${C_DATADIR}
log-file=${C_DATADIR}/logs/monero.log
log-level=1

p2p-bind-ip=0.0.0.0
p2p-bind-port=18080

rpc-bind-ip=127.0.0.1
rpc-bind-port=18081

EOF
        chmod 700 "$C_CONF"
        chown monero:monero "$C_CONF"
    fi
    if [ ! -f "$C_WALCONF" ]; then
        echo " >> Generating basic default wallet.conf into: $C_WALCONF"
        if [ ! -d "${C_DATADIR}/wallets" ]; then
            mkdir -pv "${C_DATADIR}/wallets" 
        fi
        cat > "$C_WALCONF" <<EOF
wallet-dir=${C_DATADIR}/wallets

log-file=${C_DATADIR}/logs/wallet.log
log-level=1

rpc-bind-ip=0.0.0.0
rpc-bind-port=18100
daemon-address=127.0.0.1:18081
EOF
    fi
}

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

