#!/bin/sh
### BEGIN INIT INFO
# Provides:
# Short-Description: Basic Web Server
# Description:       If enabled, start the httpd web server
### END INIT INFO

. /opt/wz_mini/wz_mini.conf

create_httpdconf()
{
  conffile="/opt/wz_mini/etc/httpd.conf"
  if [[ -f $conffile ]]; then
    rm $conffile
  fi

  if [[ "$WEB_SERVER_PASSWORD" == "" ]]; then
          WEB_SERVER_PASSWORD=$(cat /opt/wz_mini/tmp/wlan0_mac)
  fi

  webpassword=$(busybox httpd -m "$WEB_SERVER_PASSWORD")

  authline="/:$WEB_SERVER_LOGIN:$webpassword"

  cat <<EOF > $conffile
$authline
EOF

}

do_start()
{
  create_httpdconf
	if [[ "$WEB_SERVER_AUTH" == "false" ]]; then
	  httpd -p 80 -h /opt/wz_mini/www
	  echo "httpd enabled"
	elif [[ "$WEB_SERVER_AUTH" == "true" ]]; then
		httpd -p 80 -h /opt/wz_mini/www -r "Identify yourself:" -c /opt/wz_mini/etc/httpd.conf
	  echo "httpd enabled"
	fi
}
do_stop()
{

  #pkill httpd
  pidnum=$(ps | egrep "[0-9]{2} httpd -p 80" | awk '{print $1}')
  if [[ -z $pidnum ]]; then
    echo "httpd was not running"
  else
    kill $pidnum
    echo "httpd killed"
  fi

}

if [[ "$WEB_SERVER_ENABLED" == "true" ]]; then
case "$1" in
	start)
		echo "#####$(basename "$0")#####"
		do_start
		;;
	stop)
		do_stop
		;;
	restart)
		do_stop
		do_start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
		;;
esac

fi
