#!/bin/sh
# Forward modem bytes unchanged; stdout is exclusively the protocol stream.
set -eu

if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
    echo "Usage: $0 DEVICE [BAUD]" >&2
    exit 1
fi

device=$1
baud=${2-115200}
case "$device" in
    *','*|*':'*|*'!!'*)
        echo "Device path contains a socat address separator" >&2
        exit 1
        ;;
esac
if [ ! -c "$device" ]; then
    echo "Not a character device: $device" >&2
    exit 1
fi
case "$baud" in
    ''|*[!0-9]*|0)
        echo "Invalid baud rate: $baud" >&2
        exit 1
        ;;
esac
if ! command -v socat >/dev/null 2>&1; then
    echo "gammu-backend requires socat on the remote host" >&2
    exit 1
fi

# Socat 1.8 added signal-log handlers; use normal signal termination instead.
# Older socat releases do not support -S and already terminate normally.
if socat -S0 -h >/dev/null 2>&1; then
    set -- -S0
else
    set --
fi
exec socat "$@" STDIO "FILE:$device,raw,echo=0,b$baud,cs8,parenb=0,cstopb=0,cread=1,clocal=1,ixon=0,ixoff=0,crtscts=0"
