#! /bin/sh -e
# Boot Parameters to Configuration File

# This script processes the brltty= boot parameters in /proc/cmdline and
# writes a corresponding BRLTTY configuration file to /target/etc/brltty.conf.

parse()
{
    brailleDriver=""
   brailleDevice=""
   textTable=""

   found=false
   while [ "${#}" -gt 0 ]
   do
      case "${1}"
      in
         "brltty="*)
            found=true
            parameters="${1#*=}"

            number=1
            while [ "${number}" -le 3 ]
            do
               parameter="`echo ${parameters} | cut -d, -f${number}`"
               if [ -n "${parameter}" ]
               then
                  case "${number}"
                  in
                     1)
                        brailleDriver="${parameter}"
                        ;;
                     2)
                        brailleDevice=${parameter}
                        ;;
                     3)
                        textTable="${parameter}"
                        ;;
                  esac
               fi

               number="`expr ${number} + 1`"
            done
            ;;
      esac

      shift
   done

   if "${found}"
   then
      echo "# Created by ${0}"
      [ -z "${brailleDriver}" ] && brailleDriver=auto
      echo "braille-driver ${brailleDriver}"
      [ -z "${brailleDevice}" ] && brailleDevice=usb:
      echo "braille-device ${brailleDevice}"
      [ -n "${textTable}" ] && echo "text-table ${textTable}"
   fi
}

unset DEBIAN_HAS_FRONTEND
unset DEBIAN_FRONTEND
unset DEBCONF_FRONTEND
unset DEBCONF_REDIR

pid=/var/run/brltty

if [ -r $pid ] && kill -0 `cat $pid`; then
    if apt-install brltty 1>&2; then
        file="/proc/cmdline"
        if [ -f $file ]; then
            if grep brltty= $file >/dev/null ; then
                parse `cat "${file}"` >/target/etc/brltty.conf
                sed -i -e 's/^RUN_BRLTTY=.*/RUN_BRLTTY=yes/' /target/etc/default/brltty
            fi
        fi
    fi
fi

exit 0
