#!/bin/bash

logger -t arpdb-cli "arpdb-cli: launched with params '$@'"

# rlwrap arpdb-cli-simple "$@"

# yes, I know that I should use tempfile and remove it after. But I'm just too lazy for now
SOCKNAME=/tmp/$$.sock
PORT=4444
ADDR=0.0.0.0

SCRIPTNAME=$0
METHOD="new"


check() {
    MISSING=""
    for cmd in tmux socat tcpserver;do 
        which $cmd >/dev/null || MISSING="$MISSING $cmd"
    done

    if [ -n "$MISSING" ];then
        echo "Missing command(s) required to run script:$MISSING"
        exit 1
    fi
}

ARGV=( "$@" )

while [ -n "$1" ];do
    case "$1" in 
        --socket)
            shift
            SOCKNAME="$1"
            shift
            ;;

        --method)
            shift
            METHOD="$1"
            shift
            ;;

        --server)
            CMD="socat - UNIX-LISTEN:$SOCKNAME"
            if [ "$METHOD" = "split" ];then
                tmux split-window "$CMD"
                tmux select-layout tiled
            else
                tmux new-window "$CMD"
            fi
            while [ ! -S $SOCKNAME ];do
                sleep 1
            done
            socat - UNIX-CONNECT:$SOCKNAME
            exit 0
            ;;

        --port)
            shift
            PORT="$1"
            shift
            ;;

        --addr)
            shift
            ADDR="$1"
            shift
            ;;

        -h|--help)
            echo "usage: $SCRIPTNAME [-h] [--addr <ip addr>] [--port <ip port>] [--method <method>]"
            echo ""
            echo "listen on --addr address (default 0.0.0.0) and --port (default 4444)"
            echo "for each incoming connection, open tmux new window with terminal to "
            echo "that session"
            echo "written for accepting reverse pdb connections"
            echo ""
            echo "if method == split, then incoming connection will be in splitted tile. "
            echo "If method == new, then incoming connection will be in new tmux tab/window(default)"
            echo ""
            exit 1
            ;;
        *)
            echo "unknown parameter '$1'"
            exit 1
            ;;
    esac
done

check || exit 1

if [ -z "$TMUX" ];then
    echo "launch self inside tmux"
    tmux new -- $0 ${ARGV[@]}
    exit 0
fi

echo "[running server on $ADDR:$PORT]"
tcpserver $ADDR $PORT $SCRIPTNAME  --method "$METHOD" --server

