#!/bin/bash
usage="$(basename "$0") [-h] [-q] [-t timeout] [-c command] -- shell for bcm service

where:
    -h  show this help text
    -t  inactivity timeout in seconds (default 300 seconds, 0 for no timeout)
    -q  quiet, no banner (default: verbose)
    -c  command to execute directly (non-interactive)"

banner="Press Enter to show prompt.
Press Ctrl+C to exit.
NOTICE: Only one bcmsh or bcmcmd can connect to the shell at same time.
"

# Defaults
quiet=false
timeout=300
command=""

# Added 'c:' to getopts to accept a command argument
while getopts 'hqt:c:' option; do
  case "$option" in
    h) echo "$usage"
       exit
       ;;
    q) quiet=true
       ;;
    t) timeout=$OPTARG
       ;;
    c) command=$OPTARG
       ;;
   \?) printf "illegal option: -%s\n" "$OPTARG" >&2
       echo "$usage" >&2
       exit 1
       ;;
  esac
done
shift $((OPTIND - 1))

# Also allow passing the command as a trailing argument if -c wasn't used
if [ -z "$command" ] && [ $# -gt 0 ]; then
    command="$*"
fi
# Execution Logic
if [ -n "$command" ]; then
    # --- NON-INTERACTIVE MODE ---
    # Echo the command and pipe it into socat (STDIN instead of readline)
    (echo ""; sleep 0.2; echo "$command") | /usr/bin/socat -T$timeout - UNIX-CONNECT:/var/run/sswsyncd/sswsyncd.socket
else
    # --- INTERACTIVE MODE ---
    if [ "$quiet" = false ]; then
        echo "$banner"
    fi
    /usr/bin/socat -T$timeout readline UNIX-CONNECT:/var/run/sswsyncd/sswsyncd.socket
fi