#!/bin/ksh

if [[ $1 != firstrun ]]; then
  echo This script is intended for calling by pkg_add during initial
  echo installation to setup the default configuration. It is not meant
  echo to be run manually.
  exit 1
fi

if [[ -e /etc/raddb/attrs ]]; then
  echo You have a file indicating that you are trying to upgrade from
  echo FreeRADIUS 2.x to 3.x with existing configuration. You should move
  echo /etc/raddb out of the way, reinstall, and rebuild configuration
  echo based on your old setup. For more information, see
  echo https://github.com/FreeRADIUS/freeradius-server/blob/v3.0.x/raddb/README.rst
  exit 1
fi

# if any of these exist, we are already configured and should bail out
if [[ -e /etc/raddb/hints || -e /etc/raddb/huntgroups || \
	-e /etc/raddb/users || -e /etc/raddb/certs/server.pem || \
	-d /etc/raddb/mods-enabled || -d /etc/raddb/sites-enabled ]]; then
  exit 0
fi

echo '===>  Copying initial configuration'
ln -s mods-config/preprocess/hints /etc/raddb/hints
ln -s mods-config/preprocess/huntgroups /etc/raddb/huntgroups
ln -s mods-config/files/authorize /etc/raddb/users
cp -R /usr/local/share/examples/freeradius/mods-enabled /etc/raddb/
cp -R /usr/local/share/examples/freeradius/sites-enabled /etc/raddb/
echo '===>  Generating self-signed keys, this will take a few minutes'
su -l -s /bin/sh _freeradius -c 'umask 007; /etc/raddb/certs/bootstrap > /dev/null'
echo '===>  Please note: to avoid conflicting with radiusd in base,'
echo "      for debug mode use the full path: /usr/local/sbin/radiusd -X"
