#!/bin/sh

base_path=/usr/local/channels-dvr
pidfile=/var/run/channels-dvr.pid
DAEMON=$base_path/latest/channels-dvr

service_start() {
  ulimit -n 8192
  /sbin/start-stop-daemon --start --pidfile $pidfile --background --make-pidfile \
    --chuid channels-dvr:channels-dvr --chdir $base_path/data \
    --startas /bin/sh -- -c "exec $DAEMON >> $base_path/data/channels-dvr.log 2>&1"
}

service_stop() {
  start-stop-daemon --stop --pidfile $pidfile --chuid channels-dvr --exec $DAEMON
  RETVAL=$?
  [ $RETVAL -eq 0 ] && [ -e "$pidfile" ] && rm -f $pidfile
}

service_status() {
  start-stop-daemon --status -q -p $pidfile
  if [ $? -eq 0 ]; then
    echo "channels-dvr running"
  else
    echo "channels-dvr stopped"
  fi
}

service_restart() {
  service_stop
  service_start
}

if ! cat /etc/passwd | grep -q channels-dvr; then
  adduser -S -g "Channels DVR" -h /usr/local/channels-dvr -H -s /bin/false -D channels-dvr
  usermod -aG video channels-dvr
  addgroup channels-dvr
  usermod -aG channels-dvr channels-dvr
fi

if ! test -d $base_path; then
  cd /usr/local
  test -f /usr/bin/curl || ln -nsf /usr/bin/ter_curl /usr/bin/curl
  curl -s -k https://getchannels.com/dvr/setup.sh | DOWNLOAD_ONLY=1 INSECURE_SSL=1 /bin/bash
  chown -R channels-dvr:channels-dvr $base_path
fi

case $1 in
  start)
    service_start
    ;;
  stop)
    service_stop
    ;;
  status|enabled)
    service_status
    ;;
  restart)
    service_restart
    ;;
  *)
    echo "Usage: `basename $0` {start|stop|status|restart}"
    exit 1
    ;;
esac

exit 0
