#
# 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/snomONE

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

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

DOWNLOAD_PATH=http://www.snomone.com/downloads/snomONE

#
# 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

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

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

. /etc/rc.subr

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

chmod a+rx snomone

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

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