#!/bin/bash
# Copyright (C) 2000,2017 by Massimiliano Ghilardi
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
#

FIRSTARG=1
MODE=normal
DPY=

#echo "twstart: $# arguments [$@]"

for ARG
do
  #echo "twstart: now parsing [$ARG]"
  if [ "$FIRSTARG" = 1 ]; then
    set --
    FIRSTARG=0
  fi
  if [ "$MODE" = normal ]; then
    case "$ARG" in
      -h|--help|-help )
        echo "Usage: twstart [OPTIONS]
Attach a running twin server to a display or start a new server.
If a twin server is found, \`twdisplay' is used to attach it to a display,
else a new twin server is started.

Currently known options:

 -h, --help            show this help and exit
 --twin@<TWDISPLAY>    specify server to contact instead of autodetecting it
 <TWDISPLAY>           shortcut for --twin@<TWDISPLAY>
 --                    end of options: pass further args to twin or twdisplay
 --<OPTION>            other options are passed verbatim to twin or twdisplay
"
        exit 0
        ;;
      -- )
        # end of twstart options, pass the rest to twin or twdisplay
        MODE=literal
        ;;
      --twin@* )
        DPY="${ARG:7}";
        ;;
      -twin@* )
        DPY="${ARG:6}";
        ;;
      --*|-* )
        # accumulate current argument
        set -- "$@" "$ARG"
        ;;
      *:[0-9a-fA-F]* )
        DPY="$ARG";
        ;;
      * )
        echo "twstart: unknown option \`$ARG\'
try \`twstart --help\' for usage summary."
        exit 1
        ;;
    esac
  else
    # accumulate current argument
    set -- "$@" "$ARG"
  fi
  #echo "twstart: accumulated arguments [$@]"
done

if [ "$DPY" ]; then
  DPY="`twfindtwin \"$DPY\"`"
else
  DPY="`twfindtwin`"
fi

if [ "$DPY" ]; then
  echo "twstart: detected twin running on $DPY"
  exec twdisplay --twin@"$DPY" "$@"
else
  exec twin "$@"
fi

