#!/bin/bash

# opencocon option menu

SELECT=/tmp/.cocon.optmenu.select
NTP_HOSTN=/tmp/.cocon.ntp.hostname
TZ_FILEN=/tmp/.cocon.tz


# If copy-to-ram mode, show eject menu.
if [ "$COCON_COPYTORAM" = "1" ];
then
  menu_eject="EJECT"
  menu_eject_desc="Eject unused boot device"
else
  menu_eject="----"
fi


while :
do

  dialog --no-cancel --menu "Option, Ambient tools" 20 60 25 \
  MIX   "Sound mixer" \
  SNDT  "Sound test (Caution: play noise sound!)" \
  TPAD  "Touchpad calibration" \
  IMAGE "Image viewer (Incomplete)" \
  RANDR "Change resolution, output of screen" \
  KBD   "Change keyboard layout" \
  TZ    "Set timezone" \
  NTP   "Adjust clock using NTP" \
  SH    "Run shell" \
  "$menu_eject" "$menu_eject_desc" \
  RET   "Return to main menu" 2>$SELECT

  select=`cat $SELECT`

  case $select in
  MIX)
    alsamixer
    ;;

  SNDT)
    aplay /usr/share/sounds/alsa/Noise.wav
    ;;

  TPAD)
    xinput_calibrator_once.sh
    ;;

  IMAGE)
    ssdir="/media/cf/media/realroot/coconpic/"
    if [ -d "$ssdir" ];
    then
      echo "Using slideshow directory on realroot"
    else
      echo "Using pre-installed slideshow"
      ssdir="/usr/share/cocon/pic/"
    fi
     
    viewnior --slideshow --fullscreen $ssdir
    ;;

  RANDR)
    lxrandr
    ;;

  KBD)
    cocon-select-kbd
    ;;

  EJECT)
    # TODO: use sudo
    su -c "eject.eject $ROOT_DEVICE"
    ;;

  RET)
    exit 1
    ;;

  TZ)
      dialog --inputbox "Enter Timezone file (ex: Asia/Tokyo . If empty, no change timezone.)" 8 40 2>$TZ_FILEN

       tz_filenm=` cat $TZ_FILEN | sed -e "s/\.\.//g" `

       # Set timezone
       if [ -f "/usr/share/zoneinfo/$tz_filenm" ];
       then
         su -c "ln -sf /usr/share/zoneinfo/$tz_filenm /etc/localtime"
       fi

    ;;

  NTP)
      dialog --inputbox "Enter NTP Server to connect (If empty, connect to ntppool.)" 8 40 2>$NTP_HOSTN

      ntp_host=`cat $NTP_HOSTN`

      if [ -z "$ntp_host" ];
      then
        ntp_host="` echo $((RANDOM % 4)) `.opencocon.pool.ntp.org"
      fi
      if [ -n "$ntp_host" ];
      then
        su -c "ntpdate $ntp_host"
      fi
  ;;

  SH)
      /bin/bash
  ;;

  esac

done

