#!/bin/sh
#
# Configure Mouse event server

cfg=/etc/gpm.conf

get_cmdln()
{
  cmdln=
  if [ -n "$device" ]; then cmdln="$cmdln -m $device"; fi
  if [ -n "$type" ]; then cmdln="$cmdln -t $type"; fi
  if [ -n "$responsiveness" ]; then cmdln="$cmdln -r $responsiveness"; fi
  if [ -n "$append" ]; then cmdln="$cmdln $append"; fi
  echo $cmdln
}

type_help()
{
    echo "Enter ms   for Microsoft (2 or 3 button)"
    echo "      bare for Microsoft 2 button (i.e. forcing 2 button)"
    echo "      msc  for MouseSystems"
    echo "      mman for Logitech MouseMan"
    echo "      bm   for a Busmouse"
    echo "      logi for an old Logitech mouse"
    echo "      ps2  for a PS/2 mouse"
    echo "      mm   for MMSeries mouse"
    echo "Default is ms"
}

gpm_test()
{
  if [ "$restart" = "yes" ]; then
    gpmpid=`pidof -o %PPID -o $$ gpm`
    gpmcmdln=`cat /proc/$gpmpid/cmdline|tr '\0' ' '|cut -d' ' -f2-`
    kill -9 $gpmpid
  fi
  gpm `get_cmdln`

  echo "gpm `get_cmdln`"
  echo "Finish testing by typing Ctrl-D"
  cat > /dev/null
  killall -9 gpm
  if [ "$restart" = "yes" ]; then
    gpm $gpmcmdln
  fi
}

if [ -f $cfg ]; then
  . $cfg
fi

if [ $# -gt 0 -a "$1" = "--norestart" ]; then
  restart=no
else
  restart=yes
fi

echo "Configuring gpm (mouse event server):"

ok=no
while [ ! "$ok" = "yes" ]; do
  echo; echo "Actual configuration: `get_cmdln`"

  echo -n "Do you want to change anything (Y/n)? "; read answer
  if [ "$answer" = "N" -o "$answer" = "n" ]; then
    ok=yes
  else
    echo "Where is your mouse [$device]? "; echo -n "> "; read answer
    if [ -n "$answer" ]; then device="$answer"; fi
    answer=
    while [ -z "$answer" ]; do
      echo "What type is your mouse (or help) [$type]? "; echo -n "> "; read answer
      if [ -n "$answer" ]; then
        case $answer in
        bare|ms|msc|mman|mm|bm|logi|ps2)
	  type=$answer
	  ;;
        h|help)
	  type_help
	  answer=
	  ;;
        *)
	  echo "Illegal answer."
	  answer=
	  ;;
        esac
      else
	if [ -n "$type" ]; then
	  answer=$type
	fi
      fi
    done
    echo "Set the responsiveness (normally not needed) [$responsiveness]? "; echo -n "> "; read answer
    if [ -n "$answer" ]; then responsiveness="$answer"; fi
    echo "Do you want to add any additional arguments [$append]? "; echo -n "> "; read answer
    if [ -n "$answer" ]; then append="$answer"; fi
    echo -n "Do you want to test this configuration (y/N)? "; read answer
    if [ "$answer" = "Y" -o "$answer" = "y" ]; then gpm_test; fi
  fi
  
done

if [ -n "$device" -a "$device" != "/dev/mouse" ]; then
  rm -f /dev/mouse
  (cd /dev; ln -sf `echo $device|cut -d/ -f3` mouse)
fi

cat $cfg \
  | sed \
    -e "s,^[ ]*device=.*,device=$device,g" \
    -e "s,^[ ]*type=.*,type=$type,g" \
    -e "s,^[ ]*responsiveness=.*,responsiveness=$responsiveness,g" \
    -e "s,^[ ]*append=.*,append=\"$append\",g" \
  > $cfg.new
mv -f $cfg.new $cfg

  if [ "$restart" = "yes" ]; then
    /etc/init.d/gpm start
  fi
