#!/bin/sh
##
# Installs iRAPP Proxy Server 
# Mac OS X 10.4+
#
# Copyright (C) 2006-2011, Code Rebel LLC. 
# All rights reserved. 
##

if [ $UID -ne 0 ] ; then
   echo   "ERROR: You have not permissions to install iRAPP Proxy Server."
   echo   "Please use \"sudo\", e.g: sudo rapproxy_mac_install"
   exit 1
fi

if [ ! -f "./rapproxyctl" ] || \
   [ ! -f "./com.coderebel.rapproxyd.plist" ] || \
   [ ! -f "./rapproxyd.cfg.sample" ] || \
   [ ! -f "./rapproxyd" ] ; then
   echo   "fault: Source directory does not contain needed setup files."
   exit 1
fi

perm_set_rwx()
{
  chmod u=rwx,g=rx,o=rx "$1"
  chown root "$1" 
  return $?
}

perm_set_rw()
{
  chmod u=rw,g=r,o=r "$1"
  chown root "$1" 
  return $?
}

echo   "Installing iRAPP Proxy Server..."

#Install binaries and scripts

cp "./rapproxyctl"  "/usr/sbin/"
cp "./rapproxyd"  "/usr/sbin/"
if [ "$?" != "0" ] ; then
   echo   "fault: Could not copy executable files."
   exit 1
fi 
 
perm_set_rwx "/usr/sbin/rapproxyctl"
perm_set_rwx "/usr/sbin/rapproxyd" 

#Setup the daemon

if [ ! -d "/System/Library/LaunchDaemons" ] ; then mkdir -p "/System/Library/LaunchDaemons" ; fi
cp "./com.coderebel.rapproxyd.plist" "/System/Library/LaunchDaemons/"
if [ "$?" != "0" ] ; then
   echo   "fault: Could not configure daemon file."
   exit 1
fi 
perm_set_rw "/System/Library/LaunchDaemons/com.coderebel.rapproxyd.plist"

#Install config sample

if [ ! -d "/etc/irapp" ] ; then mkdir -p "/etc/irapp" ; fi
cp "./rapproxyd.cfg.sample" "/etc/irapp/"
if [ "$?" != "0" ] ; then
   echo   "fault: Could not copy configuration sample."
   exit 1
fi 

perm_set_rw "/etc/irapp/rapproxyd.cfg.sample"

echo   "Done."

if [ ! -f "/etc/irapp/rapproxyd.cfg" ] ; then
   #cp "/etc/irapp/rapproxyd.cfg.sample" "/etc/irapp/rapproxyd.cfg"
   echo "NOTE: Please create \"/etc/irapp/rapproxyd.cfg\" before starting iRAPP Proxy"
   echo "Sample configuration file: \"/etc/irapp/rapproxyd.cfg.sample\"" 
fi

exit 0
