#!/bin/sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/lighttpd
NAME=lighttpd
DESC="Lighttpd Web Server"
OPTS="-m /usr/lib -f /etc/lighttpd.conf"

if [ ! -f "/etc/lighttpd/server.pem" ]; then
  if [ ! -d /etc/lighttpd ]; then mkdir /etc/lighttpd; fi
  OPENSSL_CONF=/etc/openssl.cnf /usr/bin/openssl req -x509 -sha256 -new -newkey rsa:2048 -days 36500 -nodes -subj "/C=RU/ST=Russia/L=Yekaterinburg/O=BioSmart/OU=Biometrics/CN=localhost" -config /etc/openssl.cnf -keyout /etc/lighttpd/server.key -out /etc/lighttpd/server.cr
  cat /etc/lighttpd/server.key /etc/lighttpd/server.crt > /etc/lighttpd/server.pem
  rm /etc/lighttpd/server.key /etc/lighttpd/server.crt
fi

# Print a self signed certificate
#OPENSSL_CONF=/etc/openssl.cnf /usr/bin/openssl x509 -in /etc/lighttpd/server.pem -text -noout
# Print a signing request
#OPENSSL_CONF=/etc/openssl.cnf /usr/bin/openssl req -in /etc/lighttpd/server.pem -text -noout


case "$1" in
  start)
        echo -n "Starting $DESC: "
        start-stop-daemon --start -x "$DAEMON" -- $OPTS
        echo "$NAME."
        ;;
  stop)
        echo -n "Stopping $DESC: "
        start-stop-daemon --stop -x "$DAEMON"
        echo "$NAME."
        ;;
  restart|force-reload)
        echo -n "Restarting $DESC: "
        start-stop-daemon --stop -x "$DAEMON"
        sleep 1
        start-stop-daemon --start -x "$DAEMON" -- $OPTS
        echo "$NAME."
        ;;
  *)
        N=/etc/init.d/$NAME
        echo "Usage: $N {start|stop|restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0

