#!/bin/sh

: ${USER_HOME="/var/spool/ipfs"}
: ${USER_NAME="ipfs"}
: ${IPFS_PATH="/var/lib/ipfs"}

add_ipfs_user() {
    # If the ipfs user does not exist, create it.
    if ! grep -q -E "^${USER_NAME}:" /etc/passwd; then
        echo "Could not find user '${USER_NAME}' - creating user '${USER_NAME}' with disabled password"
        adduser --gecos "" --home "${USER_HOME}" --disabled-password "${USER_NAME}"
        echo "export IPFS_PATH=\"$IPFS_PATH\"" >> "${USER_HOME}/.bashrc"
        echo "export IPFS_PATH=\"$IPFS_PATH\"" >> "${USER_HOME}/.zshrc"

    fi
}

gen_ipfs_conf() {
    if [ ! -d "$IPFS_PATH" ]; then
        echo " >> Folder $IPFS_PATH does not exist. Creating it..."
        mkdir -p "$IPFS_PATH"
        chown "${USER_NAME}:${USER_NAME}" "$IPFS_PATH"
    fi
    if [ ! -d "/ipfs" ]; then
        echo " >> Folder /ipfs does not exist. Creating it..."
        mkdir -p "/ipfs"
    fi
    if [ ! -d "/ipns" ]; then
        echo " >> Folder /ipns does not exist. Creating it..."
        mkdir -p "/ipns"
    fi
    chown "${USER_NAME}:${USER_NAME}" /ipfs /ipns
    if ! [ -d "${USER_HOME}/.ipfs" ] && ! [ -f "${USER_HOME}/.ipfs" ]; then
        echo " >> Symlink at ${USER_HOME}/.ipfs to $IPFS_PATH does not exist. Creating it..."
        ln -s "$IPFS_PATH" "${USER_HOME}/.ipfs"
    fi
    if [ -f "${HOME}/.bashrc" ] && ! grep -q 'IPFS_PATH' "${HOME}/.bashrc"; then
        echo " >> Your shell config ${HOME}/.bashrc is missing an IPFS_PATH export. Appending one now..."
        echo -e "\nexport IPFS_PATH=\"$IPFS_PATH\"\n" >> "${HOME}/.bashrc"
    fi
    if [ -f "${HOME}/.zshrc" ] && ! grep -q 'IPFS_PATH' "${HOME}/.zshrc"; then
        echo " >> Your shell config ${HOME}/.zshrc is missing an IPFS_PATH export. Appending one now..."
        echo -e "\nexport IPFS_PATH=\"$IPFS_PATH\"\n" >> "${HOME}/.zshrc"
    fi
}

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

