#!/bin/zsh

# options
local db=:server:nosql:default
local port=5050
while getopts d:p: name
do
    case $name in
        d) db=:server:nosql:$OPTARG ;;
        p) port=$OPTARG ;; # checking for numerics is for losers
    esac
done

# init
zmodload zsh/net/tcp
ztcp -l $port
local fd=$REPLY
ztcp -a $fd
local clientfd=$REPLY

# util and cleanup
write() {
    echo "sent: $@"
    echo $@ >& $clientfd
}
trap "ztcp -c $fd; ztcp -c $clientfd" INT TERM

# loop
local get=
local getd=
local line=()
while [ 1 ]
do
    # reset
    get=
    getd=
    line=()

    # parse
    read -A line <& $clientfd
    echo "got: $line"
    case $line[1] in # I won't bother verifying # of args, too lazy tbh
        exit)   break ;;
        ping)   write pong ;;
        switch) db=:server:nosql:$line[2] ;;
        put)    zstyle $db $line[2] "$line[3,-1]" ;;
        getd)   zstyle -s $db $line[2] getd || getd=$line[3] ;&
        get)    zstyle -s $db $line[2] get || get=$getd; write $get ;;
    esac
done