#!/bin/bash
# customization parameters
ttyprefix=/dev/tty ;# what to add to ttycolumn's word to obtain valid device
cmdcolumn=5 ;# where to find command in ps output
ttycolumn=2 ;# where to find tty name in ps output

# displays usage information
usage () {
 echo "xtitle [ -t tty|-c command] [-i|-w|-f] title" >&2
 echo " -t specifies tty associated with xterm to change" >&2
 echo " -c specifies command running in this xterm" >&2
 echo " -i notifies, that only icon name should be changed" >&2
 echo " -w that window name only (default - both)">&2
 echo " -f changes font instead of title" >&2
}
# tries to get tty name from command name
get_tty_from_command () {
  local t
  t=`ps |awk "\\$$cmdcolumn~/$1/ {print \"$ttyprefix\" \\$$ttycolumn;exit}"`
  if [ -z "$t" ]
     then
       echo "None of your processes matches pattern \"$1\"" >&2
       exit 1
     fi
  check_tty $t
}
# checks if supplied tty name is valid device name
check_tty () {
  if [ ! -c $1 ] 
     then
       echo "$i is not valid tty name" >&2
       exit 1
     fi
  if [ ! -w $1 ]
     then
       echo "$i is not writable for you" >&2
       exit 1
     fi
  tty=$1
}
# by default change our own xterm title
tty=`tty`
# by default change both window name and icon name
mode=0
for i
do
       case $i
       in 
	  -i) mode=1;shift;;
          -w) mode=2;shift;;
          -f) mode=50;shift ;;
	  -t) check_tty $2;shift;shift;;
          -c) get_tty_from_command $2;shift;shift;;
          -h) echo "$0: changes a title of xterm window" 
              usage 
              exit 0 
             ;;
          --) shift; break;;
          -*) echo "Invalid option $1. Usage:">&2
              usage
              exit 1;;
          *) break;;
       esac
       
done
echo -e "\\033]$mode;$*\a\c" >$tty 

