#!/bin/bash
if [[ $# -lt 1 || $# -gt 5 ]] ; then
  echo "USAGE: $0 full_name username organization email phone"
  exit 1
fi

if [[ $(psql -d ossdip -U postgres -tA -c "SELECT COUNT(*) FROM users WHERE username = '$2'") -gt 0 ]] ; then
  echo "User exists in DB"
  exit 1
fi

ssh -n vpnvpn "test -f /var/opt/users/${2}.ovpn"
if [[ $? -eq 0 ]] ; then
  echo "User exists on VPN Server"
  exit 1
fi

vpn_pass=$(/opt/users/bin/mkpasswd)
logger "Create new user ${2} in local database"
psql -d ossdip -U postgres -c "call create_user('$1', '$2', '$3', '$vpn_pass', '$4', '$5');"

logger "Create new user ${2} on vpn server"
ssh -n vpnvpn "/opt/bin/add_user ${2}"
