#!/bin/bash
#
# Installs app if not already installed
. /etc/federated
. /federated/lib/functions.sh
trap cleanup `seq 1 15`

usage() {
cat << EOF
Install application
Usage: $0 [-n] appname
Arguments:
    appname         Application to install. bookstack,espocrm,freescout,etc

Options
    -n              Don't send the customer e-mail on install

EOF
exit 2;
}

while getopts "n" OPTION; do
  case $OPTION in
    n)
      NO_EMAIL="true";
      ;;
    *)
      usage;
      exit 2;
  esac
done

[ $# -gt 2 ] || [ $# -lt 1 ] && usage
[[ "$2" = "-n" ]] && usage
[[ ! "$NO_EMAIL" ]] && APP=$1 || APP=$2

[ ! -f /federated/lib/$APP.sh ] && failcheck "/federated/lib/$APP.sh doesn't exist."
[ -d /federated/apps/$APP ] && failcheck "/federated/apps/$APP already exists. $APP is installed?"
. /federated/lib/$APP.sh
config_$APP
start_$APP
# Only send email if email function exists and NO_EMAIL isn't set
if [[ ! "$NO_EMAIL" ]] && [[ -d "/federated/apps/mail" ]] && [[ $(type -t email_$APP) == function ]]; then
  email_$APP
fi
