#!/bin/sh -e

### BEGIN INIT INFO
# Provides:          oled
# Required-Start:    $network $local_fs
# Required-Stop:     $network $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Asus OLED service
### END INIT INFO

test $DEBIAN_SCRIPT_DEBUG && set -v -x

ASUSOLED=/usr/bin/asusoled
DESC="ASUS OLED screen daemon"

BLANKOLED=/usr/share/pixmaps/asusoled-blank.png

test -x $ASUSOLED || exit 0
test -f $BLANKOLED || exit 0

# Source defaults file; edit that file to configure this script.
DISABLED=0
if test -e /etc/default/asusoled ; then
  . /etc/default/asusoled
fi

start_vpn () {
    if grep -q '^[	 ]*daemon' $CONFIG_DIR/$NAME.conf ; then
      # daemon already given in config file
      DAEMONARG=
    else
      # need to daemonize
      DAEMONARG="--daemon ovpn-$NAME"
    fi

    if grep -q '^[	 ]*status ' $CONFIG_DIR/$NAME.conf ; then
      # status file already given in config file
      STATUSARG=""
    elif test $STATUSREFRESH -eq 0 ; then
      # default status file disabled in /etc/default/openvpn
      STATUSARG=""
    else
      # prepare default status file
      STATUSARG="--status /var/run/openvpn.$NAME.status $STATUSREFRESH"
    fi

    echo -n " $NAME"
    STATUS="OK"

    # Check to see if it's already started...
    if test -e /var/run/openvpn.$NAME.pid ; then
      STATUS="FAILED - Already running (PID file exists)"
    else
      $DAEMON --writepid /var/run/openvpn.$NAME.pid \
	      $DAEMONARG $STATUSARG --cd $CONFIG_DIR \
	      --config $CONFIG_DIR/$NAME.conf < /dev/null || STATUS="FAILED"
    fi
    echo -n "($STATUS)"
}
stop_vpn () {
  kill `cat $PIDFILE` || true
  rm $PIDFILE
  rm -f /var/run/openvpn.$NAME.status 2> /dev/null
}

case "$1" in
start)
  echo -n "Starting $DESC:"

  # check if automatic startup is disabled by AUTOSTART=none
  if test "$DISABLED" = "1"; then
     /usr/bin/asusoled -d
    echo " OLED disabled."
    exit 0
  fi

  /usr/bin/asusoled -e

  # We update the screen every second.
  /bin/sh -c 'while test "1" = "1"; do
    /bin/cp /usr/share/pixmaps/asusoled-blank.png /tmp/oled.png
    /usr/bin/mogrify -fill white -pointsize 15 -annotate 0x0+2+15 `date "+%d/%m/%Y"` /tmp/oled.png
    /usr/bin/mogrify -fill white -pointsize 15 -annotate 0x0+2+31 `date "+%H:%M:%S"` /tmp/oled.png
    /usr/bin/asusoled -s /tmp/oled.png
    /bin/sleep 1
  done' &

  echo "."

  ;;

stop)
  echo "."
  ;;

*)
  echo "Usage: $0 {start|stop}" >&2
  exit 1
  ;;
esac

exit 0


