#!/bin/sh

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

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

gen_blurt_conf() {
    if [ ! -d "/blurt" ]; then
        echo " >> Folder /blurt does not exist. Creating it..."
        mkdir -p /blurt
    fi
    if [ ! -f "/blurt/config.ini" ]; then
        echo " >> File /blurt/config.ini does not exist. Creating it..."
        wget -O /blurt/config.ini https://gitlab.com/blurt/blurt/-/raw/dev/doc/witnesses/config.ini
    fi
    if [ ! -f "/blurt/snapshot.json" ]; then
        echo " >> File /blurt/snapshot.json does not exist. Creating it..."
        wget -O /blurt/snapshot.json https://cloudflare-ipfs.com/ipfs/QmPrwVpwe4Ya46CN9LXNnrUdWvaDLMwFetMUdpcdpjFbyu
    fi
    chown -R blurt:blurt /blurt
}

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

