#!/bin/sh
. /opt/lora/etc/settings
. /etc/rc.d/init.d/functions

case "$1" in
  start|restart)
    if [ "$1" = "restart" ]; then
      echo -n "Restarting RESTful: "
      killall mhttpd 2> /dev/null
      del_chain srv_http filter
      del_chain6 srv_http filter
    else
      echo -n "Starting RESTful: "
    fi
    if [ "$LORA_RESTFUL_HTTP" != "1" ] && [ "$LORA_RESTFUL_HTTPS" != "1" ]; then
      echo "skipped"
      exit 0
    fi
    OPTS=""
    if [ "$LORA_RESTFUL_HTTP" != "1" ]; then
      OPTS="$OPTS --no-http"
    fi
    if [ "$LORA_RESTFUL_HTTPS" != "1" ]; then
      OPTS="$OPTS --no-https"
    fi

    if [ -e /etc/certs/https ] || [ ! -s /etc/certs/https_cert ] || [ ! -s /etc/certs/https_key ]; then
      export RANDFILE=/tmp/rnd
      touch /etc/certs/https
      /usr/bin/mac - | /usr/bin/openssl req -new -newkey rsa:2048 -nodes -out /tmp/csr -keyout /etc/certs/https_key 2> /dev/null
      /usr/bin/openssl x509 -req -sha256 -setstart 700101000000Z -setend 400101000000Z -in /tmp/csr -signkey /etc/certs/https_key -out /etc/certs/https_cert -extensions v3_req -extfile /usr/ssl/openssl.cnf 2> /dev/null
      chmod 600 /etc/certs/https_key
      rm /tmp/csr /etc/certs/https
    fi
    add_chain srv_restful filter
    add_rule srv_restful tcp 81
    add_chain6 srv_restful filter
    add_rule6 srv_restful tcp 81
    if [ "$LORA_RESTFUL_HTTPS" = "1" ]; then
      add_rule srv_restful tcp 8445
      add_rule6 srv_restful tcp 8445
    fi
    /opt/lora/bin/RESTful $OPTS >/dev/null &
    RETVAL=$?
    if [ $RETVAL = 0 ]; then echo "done"; else echo "failed"; fi
    exit $RETVAL
    ;;
  stop)
    echo -n "Stopping RESTful "
    killall RESTful 2> /dev/null
    RETVAL=$?
    del_chain srv_restful filter
    del_chain6 srv_restful filter
    if [ $RETVAL = 0 ]; then echo "done"; else echo "failed"; fi
    exit $RETVAL
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}"
    exit 1
esac
