#!/bin/sh

set -e

BASE_HTTP_PORT=874
BASE_RTSP_PORT=8574
GROUP_SZ=6
MAX_CAMS=24
APPNAME=`basename $0`
DIR='./'

usage()
{
   echo "Usage: $APPNAME [opts] empty-temp-dir"
   echo "\twhere opts:"
   echo "\t\t-h           - print this help"
   echo "\t\t-c NBR       - max cameras numbers into AVReg conf, default $MAX_CAMS"
   echo "\t\t-g NUM       - max cameras per profile (process avregd), default $GROUP_SZ"
   echo "\t\t-p HTTP_PORT - base avregd http server port, default $BASE_HTTP_PORT"
   echo "\t\t-r RTSP_PORT - base avregd rtsp server port, default $BASE_RTSP_PORT"
}

print_profile()
{
   local min_cam=$1 max_cam=$2 http_port=$3 rtsp_port=$4
   cat <<EOF
devlist = $min_cam - $max_cam

avregd {
    http-port = $http_port
    rtsp-port = $rtsp_port
}

avreg-site {
    avregd-httpd = 'http://\$_SERVER[SERVER_NAME]:$http_port'
}
EOF
}

while getopts "hc:p:g:" opt; do
   case $opt in
      h)
         usage >&2
         exit 1
         ;;
      c)
         MAX_CAMS=$(( $OPTARG / 1 ))
         ;;
      g)
         GROUP_SZ=$(( $OPTARG / 1 ))
         ;;
      p)
         BASE_HTTP_PORT=$(( $OPTARG / 1 ))
         ;;
      r)
         BASE_RTSP_PORT=$(( $OPTARG / 1 ))
         ;;
      :)
         echo "Option -$OPTARG requires an argument." >&2
         usage >&2
         exit 1
         ;;
      *)
         usage >&2
         exit 1
         ;;
   esac
done

shift $(( OPTIND - 1 ))

if [ -n "$1" ]; then
   DIR="$1"
fi

if [ ! -d "$DIR" ]; then
   echo "$DIR is not a directory." >&2
   usage >&2
   exit 1
fi

if [ -n "$(ls -A $DIR)" ]; then
   echo "$DIR is not a empty directory." >&2
   usage >&2
   exit 1
fi

cam_start=1
http_port=$BASE_HTTP_PORT
rtsp_port=$BASE_RTSP_PORT
a=${#MAX_CAMS}

while :
do
   cam_end=$(( cam_start + GROUP_SZ - 1 ))
   profile_name=`printf "c%.${a}u-%.${a}u" $cam_start $cam_end`

   print_profile $cam_start $cam_end $http_port $rtsp_port > "$DIR/$profile_name"

   [ $cam_end -ge $MAX_CAMS ] && break
   cam_start=$(( cam_start + GROUP_SZ ))
   http_port=$(( http_port + 1 ))
   rtsp_port=$(( rtsp_port + 1 ))
done
