#
# Installer for snom ONE on FreeBSD
#
# TODO:
# Decide what languages you want installed (for audio). Valid languages are:
# dk: Danish
# nl: Dutch
# uk: English (UK)
# en: English (US)
# ca: French (Canada)
# fr: French (France)
# de: German
# gr: Greek
# it: Italian
# pl: Polish
# ru: Russian
# sp: Spanish
# se: Swedish
# tr: Turkish
LANGUAGES="en de"

# TODO:
# Decide where to put all the stuff:
PBX_DIR=/usr/local/pbx

# TODO:
# Decide which version you want to run:
VERSION=5.2.2

# Below here should be audomatic
# Find out if this is 32 or 64 bit:
BITS=`getconf LONG_BIT`

DOWNLOAD_PATH=http://www.vodia.com/downloads/pbx

#
# Check if this is root
if [ -z "$EUID" ]; then EUID=`id -u`; fi
if [ "$EUID" -ne 0 ]; then
  echo "This script must be run as root"
  exit 1
fi

#
# Make sure that the programs that we need are installed:
#
if [ -z `which wget` ]; then
  pkg_add -r wget
fi
if [ -z `which ntpd` ]; then
  pkg_add -r ntp
fi
if [ -z `which unzip` ]; then
  pkg_add -r unzip
fi


if [ ! -d $PBX_DIR ]; then
  mkdir $PBX_DIR
fi
cd $PBX_DIR

# Get the language files:
for i in $LANGUAGES moh; do
  wget $DOWNLOAD_PATH/audio/audio_$i.zip
  unzip audio_$i.zip
  rm audio_$i.zip
done

# Get the executable:
wget $DOWNLOAD_PATH/freebsd$BITS/pbxctrl-freebsd$BITS-$VERSION
wget $DOWNLOAD_PATH/pbxctrl-$VERSION.dat

mv pbxctrl-freebsd$BITS-$VERSION pbxctrl
mv pbxctrl-$VERSION.dat pbxctrl.dat
chmod a+rx pbxctrl

# Install the startup script:
cd /etc/rc.d
cat >pbx <<EOF
#!/bin/sh
# PROVIDE: pbx
# REQUIRE: LOGIN cleanvar
# KEYWORD: shutdown

. /etc/rc.subr

name="pbx"
rcvar=pbx_enable
pidfile="/var/run/pbx.pid"
command="$PBX_DIR/pbxctrl"
command_args="--dir $PBX_DIR --pidfile \$pidfile"
load_rc_config \$name
run_rc_command "\$1"
EOF

chmod a+rx pbx

# Check if the snom ONE parameters are already in /etc/rc.conf
grep pbx_enable /etc/rc.conf >/dev/null 2>/dev/null
if [ $? -ne 0 ]; then
  echo pbx_enable=\"YES\" >>/etc/rc.conf
  echo pbx_flags=\"--dir $PBX_DIR --pidfile /var/run/pbx.pid\" >>/etc/rc.conf
fi

# Start the service:
/etc/rc.d/pbx start
