#!/bin/sh
# Helper script which auto-gens a new SSL key for each start
# of the sysadm server

ssl_keygen()
{
  if [ ! -d "/usr/local/etc/sysadm" ] ; then
    mkdir -p /usr/local/etc/sysadm
  fi
  if [ "$1" = "-rest" ] ; then
    openssl req -x509 -nodes -newkey rsa:2048 \
       -keyout /usr/local/etc/sysadm/restserver.key \
       -out /usr/local/etc/sysadm/restserver.crt -days 1024 \
       -subj "/C=US/ST=MY/L=NULL/O=SysAdm/OU=SysAdm/CN=SysAdm/emailAddress=none@example.org" 2>/dev/null
  else
    openssl req -x509 -nodes -newkey rsa:2048 \
       -keyout /usr/local/etc/sysadm/wsserver.key \
       -out /usr/local/etc/sysadm/wsserver.crt -days 1024 \
       -subj "/C=US/ST=MY/L=NULL/O=SysAdm/OU=SysAdm/CN=SysAdm/emailAddress=none@example.org" 2>/dev/null
    if [ ! -e "/usr/local/etc/sysadm/ws_bridge.key" ] ; then
      openssl req -x509 -nodes -newkey rsa:2048 \
        -keyout /usr/local/etc/sysadm/ws_bridge.key \
       -out /usr/local/etc/sysadm/ws_bridge.crt -days 102400 \
       -subj "/C=US/ST=MY/L=NULL/O=SysAdm/OU=SysAdm/CN=SysAdm/emailAddress=none@example.org" 2>/dev/null
    fi
  fi
}

export PATH="${PATH}:/usr/local/bin:/usr/local/sbin"
ssl_keygen "$1"
command="/usr/local/bin/sysadm-binary"
flags=""

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

exec $command $flags
