#!/usr/bin/env bash
#   Copyright (C) 2024 John Törnblom
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING. If not see
# <http://www.gnu.org/licenses/>

HOST=$PS5_HOST
PORT=$PS5_PORT

PAYLOAD=""
INTERACTIVE=""


show_help() {
    cat <<EOF
Usage: $(basename "$0") -h HOST [-p PORT] [-i] PAYLOAD_PATH_OR_URI

Options:
  -h HOST        Set the host address (defaults to \$PS5_HOST)
  -p PORT        Set the port (defaults to \$PS5_PORT if set, else 9021)
  -i             Enable interactive mode (append /dev/stdin to payload)
  -H, --help     Show this help message and exit

Arguments:
  PAYLOAD_PATH   Path or URI to the payload
EOF
}

if [ -z "$PORT" ]; then
    PORT=9021
fi

for arg in "$@"; do
    case "$arg" in
        --help)
            show_help
            exit 0
            ;;
    esac
done


while getopts "h:p:i" opt; do
    case ${opt} in
	h) HOST=$OPTARG;;
	p) PORT=$OPTARG;;
	i) INTERACTIVE="1";;
    esac
done
shift $((OPTIND -1))


if [[ -z $HOST || -z $PORT || -z $1 ]]; then
    echo "Usage: $(basename $0) -h HOST [-p PORT] [-i] PAYLOAD_PATH" >&2
    exit 1
fi


if [[ -z $INTERACTIVE ]]; then
    if [ -e "$1" ]; then
	socat -t 9999999 - TCP:$HOST:$PORT < $1
    else
	echo "$1" | socat -t 9999999 - TCP:$HOST:$PORT
    fi
else
    if [ -e "$1" ]; then
	{ cat "$1" && cat /dev/stdin; } | socat - TCP:$HOST:$PORT
    else
	{ echo "$1" && cat /dev/stdin; } | socat - TCP:$HOST:$PORT
    fi
fi
