#!/bin/bash

###########################################
## Simple settings manager for instantOS ##
###########################################

sq() {
    sqlite3 ~/.config/instantos/settings.db "$1"
}

case "$1" in
-b) # 1 or 0 to exit code
    shift
    BINARY=True
    ;;
-h)
    echo "usage:"
    echo "get setting: iconf setting"
    echo "set setting: iconf setting value"
    echo ""
    exit
    ;;
-i)
    # test -e for indicator files is faster than firing up sqlite
    shift
    if ! [ -e "$HOME"/.config/iconf ]; then
        mkdir "$HOME"/.config/iconf
        if [ -z "$2" ]; then
            exit 1
        fi
    fi

    if [ -z "$2" ]; then
        if [ -e "$HOME"/.config/iconf/"$1" ]; then
            exit 0
        fi
    else
        if ! [ -e "$HOME"/.config/iconf/"$1" ]; then
            touch "$HOME"/.config/iconf/"$1"
        fi
    fi
    ;;
all)
    sq 'SELECT * FROM SETTINGS'
    exit
    ;;
esac

# initialize new settings
if ! [ -e ~/.config/instantos/settings.db ]; then
    mkdir -p ~/.config/instantos
    sq 'CREATE TABLE "settings" ("setting" TEXT constraint_name PRIMARY KEY, "value" TEXT);'
    # default settings
    sq 'INSERT INTO settings (setting, value) VALUES ("welcome", "1")' # startup welcome app
fi

if [ -n "$2" ]; then
    sq 'REPLACE INTO settings (setting, value) VALUES ("'"$1"'", "'"$2"'")'
else
    if [ -z "$BINARY" ]; then
        # setting:default returns something even if there's no entry in the database
        if [[ "$1" =~ ":" ]]; then
            SETTING="${1%:*}"
            DEFAULT="${1#*:}"
        else
            SETTING="$1"
        fi

        VALUE=$(sq 'SELECT value FROM settings WHERE setting="'"$SETTING"'"')
        if [ -z "$VALUE" ]; then
            if [ -z "$DEFAULT" ]; then
                exit 1
            else
                echo "$DEFAULT"
            fi
        else
            echo "$VALUE"
        fi
    else
        VALUE=$(sq 'SELECT value FROM settings WHERE setting="'"$1"'"')
        if [ "$VALUE" = "1" ]; then
            exit 0
        else
            exit 1
        fi
    fi
fi
