#!/bin/sh

DIRBASEZAP=/usr/local/share/zaproxy/
ZAPJAR=${DIRBASEZAP}zap-2.17.0.jar
ZAPDIR=~/.ZAP
JAVA_CMD=$(javaPathHelper -c zaproxy)

for arg do
    case $arg in
        -Xmx*)
            JMEM=$arg
            ;;
        --jvmdebug*)
            JAVADEBUGPORT=$(printf '%s\n' "$arg" \
                | sed -e 's/^--jvmdebug//' -e 's/^=//')

            if [ -z "$JAVADEBUGPORT" ]; then
                JAVADEBUGPORT=1044
            fi

            JAVADEBUG="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:$JAVADEBUGPORT"
            ;;
        -dir)
            shift
            ZAPDIR=$1
            ;;
        *)
            set -- "$@" "$arg"
    esac
    shift
done

JVMPROPS="${ZAPDIR}/.ZAP_JVM.properties" 

if [ -z "$JMEM" -a -f $JVMPROPS ]; then
  # Local jvm properties file present
  JMEM=$(head -1 $JVMPROPS)
  if [ ! -z $JMEM ]; then
    echo "Read custom JVM args from $JVMPROPS"
  fi
fi

if [ -z "$JMEM" ]; then
  # Default java memory setting
  # min of 1/2 of the datasize ulimit or 1/4 physical memory
  QMEM=$(($(sysctl -n hw.physmem)/1024/1024/4))
  HMEM=$(($(ulimit -m )/1024/2 ))
  if [ "$QMEM" -lt "$HMEM" ] ; then
    JMEM="-Xmx${QMEM}m"
  else
    JMEM="-Xmx${HMEM}m"
  fi
fi

echo "Using JVM args: $JMEM"

if [ -n "$JAVADEBUG" ]
then
  echo "Setting debug: $JAVADEBUG"
fi

cd ${DIRBASEZAP}
exec ${JAVA_CMD} ${JMEM} ${JAVADEBUG} -jar "${ZAPJAR}" -dir ${ZAPDIR} -installdir ${DIRBASEZAP} "$@"
