#!/bin/bash
[ -d cert ] || mkdir cert

openssl genrsa -out cert/server.key 2048
openssl req -new -key cert/server.key -out cert/server.csr -subj "/CN=key-storage-agent"
openssl x509 -req -days 365 -in cert/server.csr -signkey cert/server.key -out cert/server.crt


mkdir -p "$HOME/tmp"
PIDFILE="$HOME/tmp/key-storage-agent.pid"

if [ -e "${PIDFILE}" ] && (ps -u $(whoami) -opid= |
                           grep -P "^\s*$(cat ${PIDFILE})$" &> /dev/null); then
  echo "Already running."
  exit 99
fi

PATH=$PATH:/usr/local/bin

nohup $GOPATH/src/code.vereign.com/code/key-storage-agent/bin/server --cert-dir $GOPATH/src/code.vereign.com/code/key-storage-agent/cert > $HOME/key-storage-agent.log 2>&1 &

echo $! > "${PIDFILE}"
chmod 644 "${PIDFILE}"
