#!/bin/bash

# Script to initialize Opennap NG user database

OPENNAP_PATH=/usr/local/share/opennap-ng/
FILENAME=opennap-users.txt
USERNAME=Elite
PASSWORD=elite
LEVEL=4
EMAIL=unknown
OUTPUT=
PREV_USERNAME=



function read_value () {
 local VAL
    read -en 50 -p "Please enter $1 [$2]: " VAL
    [ "$VAL" != "" ] && echo $VAL || echo $2
}


function verbose_level () {
    case $1 in
        1) echo "User";;
        2) echo "Moderator";;
        3) echo "Admin";;
        4) echo "Elite";;
        *) echo "";;
    esac
}


function title () {
    echo ""
    echo Opennap NG user database initialization script.
    echo ""
    echo This script allows you to create one or more user entries,
    echo preferrably of level Elite, for your new Opennap NG server.
    echo ""
}



title
while [ true ]; do
    while [ true ]; do
        while [ true ]; do
            P=$(read_value "path to Opennap NG data directory" $OPENNAP_PATH)
            [ -d "$P" ] && break
            read -en 2 -p "Directory does not exist! Create (y/n)? " CREATE
            [ "$CREATE" != "y" ] && continue
            mkdir "$P"
            break
        done
        OPENNAP_PATH="$P"
        [ ! -f "$OPENNAP_PATH/$FILENAME" ] && break
        read -en 2 -p "File $FILENAME already exists! Overwrite (y/n)? " OW
        [ "$OW" == "y" ] && break
    done
        
    while [ true ]; do
        echo ""
        while [ true ]; do
            USERNAME=$(read_value "nick (username)" $USERNAME)
            [ "$USERNAME" != "$PREV_USERNAME" ] && break
            echo '*** Error: please enter a different username!'
        done
        PASSWORD=$(read_value "password" $PASSWORD)
        EMAIL=$(read_value "email" $EMAIL)
        while [ true ]; do
            LEVEL=$(read_value "userlevel (1=User, 2=Mod, 3=Admin, 4=Elite)" $LEVEL)
            VERBLEVEL=$(verbose_level $LEVEL)
            [ "$VERBLEVEL" != "" ] && break
            echo '*** Error: invalid user level!'
        done
        echo -e "\nNick: $USERNAME   PW: $PASSWORD   Email: $EMAIL   Level: $VERBLEVEL"
        read -en 2 -p "Correct (y/n)? " CORRECT
        [ "$CORRECT" != "y" ] && continue
        PREV_USERNAME=$USERNAME
        NOW=$(date +"%s")
        OUTPUT=$(echo -e "$OUTPUT\n$USERNAME $PASSWORD $EMAIL $VERBLEVEL $NOW $NOW 0")
        read -en 2 -p "Enter another user (y/n)? " ANOTHER
        [ "$ANOTHER" != "y" ] && break
    done
    echo -e "\nA file $FILENAME with the following content will be created:\n"
    echo -e "$OUTPUT\n"
    read -en 2 -p "Correct (y/n)? " CORRECT
    [ "$CORRECT" == "y" ] && break
done
echo -e >"$OPENNAP_PATH/$FILENAME" "$OUTPUT\n"
