#!/usr/bin/env bash

help="
Usage:
  --lightd        only apply to lightd service
  --multimediad   only apply to multimediad service
  --vuid          only apply to vuid service
  --ttsd          only apply to ttsd service

Options:
  -s              serial number.

By default operation is going to be applyed to all services.

Example:
  $ ./tools/runtime-op --vuid restart
  $ ./tools/runtime-op restart
"

lightd='NO'
multimediad='NO'
vuid='NO'
ttsd='NO'
only='NO'
sn=""

args=()
while [ $# -gt 0 ]; do
  case "$1" in
    -s)
      sn="$2"
      shift
      ;;
    --lightd)
      only='YES'
      lightd='YES'
      ;;
    --multimediad)
      only='YES'
      multimediad='YES'
      ;;
    --vuid)
      only='YES'
      vuid='YES'
      ;;
    --ttsd)
      only='YES'
      ttsd='YES'
      ;;
    -h|--help)
      printf "$help"
      exit
      ;;
    -*)
      echo "Illegal option $1"
      ;;
    *)
      args=("${args[@]}" "$1")
      ;;
  esac
  shift $(( $# > 0 ? 1 : 0 ))
done

function shell() {
  if test "$sn" != ""; then
    adb -s "$sn" shell $1
  else
    adb shell $1
  fi
}

function op {
  echo "$2ing $1..."
  if test "$sn" != ""; then
    adb -s "$sn" shell "/etc/init.d/$1 $2"
  else
    adb shell "/etc/init.d/$1 $sn $2"
  fi
}

shell "mount -o remount,rw /"

if test "$only" = 'NO'; then
  lightd='YES'
  multimediad='YES'
  vuid='YES'
  ttsd='YES'
fi

if test "$lightd" = 'YES'; then
  op "lightd" "${args[0]}"
fi
if test "$multimediad" = 'YES'; then
  op "multimediad" "${args[0]}"
fi
if test "$vuid" = 'YES'; then
  op "vui-daemon" "${args[0]}"
fi
if test "$ttsd" = 'YES'; then
  op "ttsd" "${args[0]}"
fi
