#!/bin/bash
#
# Startup script, MacOSX Sandbox profile for IronSafari - the safari component of IronSuite
#
# Copyright 2010 Robert Malmgren AB. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are
# permitted provided that the following conditions are met:
#
#   1. Redistributions of source code must retain the above copyright notice, this list of
#      conditions and the following disclaimer.
#
#   2. Redistributions in binary form must reproduce the above copyright notice, this list
#      of conditions and the following disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY Robert Malmgren AB ``AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# 
# The views and conclusions contained in the software and documentation are those of the
# authors and should not be interpreted as representing official policies, either expressed
# or implied, of Robert Malmgren AB.
#
#
#

#
# The purpose of this script is to do 
# * Some search-and-replace in the ruleset (e.g. name of user running program)
# * Parse option file enable support for certain features (e.g. Java, Kerberos, flash, etc)
# * Start firefox with sandbox-exec and the right command line options
#

PATH=/bin:/usr/bin

logger -t foo "IronSafari starting!"

username=$(whoami)
processed_template_location=$(mktemp -d -t safari-sandbox)
tmpbase=$(echo $TMPDIR | sed 's/\/-Tmp-\/$//')
IS_DIR=`pwd`
IS_CONF=${IS_DIR}/IronSafari.config
IS_ADDONS=${processed_template_location}/safari-addons.sb

#
# Inspired by the checkyesno() function from the
# FreeBSD boot support routines in /etc/rc.subr
#

myyesno()
{
        case ${1} in

                #       "yes", "true", "on"
        [Yy][Ee][Ss]|[Tt][Rr][Uu][Ee]|[Oo][Nn])
                return 0
                ;;

                #       "no", "false", "off"
        [Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|[Oo][Ff][Ff]|0)
                return 1
                ;;
        *)
                echo  "${1} is not set properly. Ironfox wrapper startup script exiting."
                return 2
                ;;
        esac
}

#
# Preset some var's to default values. NOTE - Change value with IronFox.config file
#

IS_DOWNDIR=~/Downloads
IS_DEBUG=off

cp /dev/null $IS_ADDONS

if [ -f "$IS_CONF" ];
then

    for i in DEBUG LOGGING JAVA DOWNLOAD UPLOAD QUICKTIME CITRIX
    do

	# Parse the config file, get the value J for key I

	j=`cat $IS_CONF | egrep -v '^[ 	]*#'| egrep -v '^$' | grep -i $i | sed 's/[	]//g' | cut -d# -f1 | cut -d= -f2`
       
	if [ -n "$j" ];
	then
	    case $i in

		[Dd][Oo][Ww][Nn][Ll][Oo][Aa][Dd]) RDIR=`eval echo "$j"`
		      if [ ! -d  "$RDIR" ];
		      then
			logger -t sandbox "ERROR: IronSuite - The download directory configured in config file ($j - $RDIR) does not exist. Exiting"
			echo "ERROR: IronSuite - The download directory configured in config file ($j - $RDIR) does not exist. Exiting"
			exit 1
		      else
			IS_DOWNDIR="$RDIR"
		      fi
		    ;;
		[Dd][Ee][Bb][Uu][Gg]|[Ll][Oo][Gg][Gg][Ii][Nn][Gg]) 
		    myyesno "$j"
		    if [ "$?" -eq "0" ];
		    then
			IS_DEBUG="on"
		    fi
		    ;;

		[Jj][Aa][Vv][Aa])
		    myyesno "$j"
		    if [ "$?" -eq "0" ];
		    then
			echo '(import "%%PATH%%java.sb")' | sed -e "s=%%PATH%%=${processed_template_location}/=g" >>  $IS_ADDONS
		    fi
		    ;;
		[Qq][Uu][Ii][cC][kK][Tt][Ii][Mm][eE]) 
		    myyesno "$j"
		    if [ "$?" -eq "0" ];
		    then
			echo '(import "%%PATH%%quicktime.sb")' | sed -e "s=%%PATH%%=${processed_template_location}/=g" >>  $IS_ADDONS
		    fi
		    ;;
		[Cc][Ii][Tt][Rr][Ii][Xx]) 
		    myyesno "$j"
		    if [ "$?" -eq "0" ];
		    then
			echo '(import "%%PATH%%citrix.sb")' | sed -e "s=%%PATH%%=${processed_template_location}/=g" >>  $IS_ADDONS
		    fi
		    ;;
		[Uu][Pp][Ll][Oo][Aa][Dd]) RDIR=`eval echo "$j"`
		       if [ ! -d  "$RDIR" ];
		       then
			   logger -t sandbox "ERROR: IronSuite/IronSafari - The upload directory configured in config file ($j) does not exist. Exiting"
			   echo "ERROR: IronSuite/IronSafari - The upload directory configured in config file ($j) does not exist. Exiting"
			   exit 1
		       else
			IS_UPDIR="$RDIR"
		      fi
		    ;;
		*)  # This should never happen....
		    logger -t sandbox "ERROR: IronSuite/IronSafari - Malformed configure file ($IS_CONF). Keyword  ($i) not supported. Exiting"
		    echo  "ERROR: IronSuite/IronSafari - Malformed configure file ($IS_CONF). Keyword  ($i) not supported. Exiting"
		    exit 1
		    ;;
	    esac

	fi
    done
fi

echo "(allow file-read-data file-read-metadata file-write"'*'" (subpath \"$IS_DOWNDIR\"))" >>  $IS_ADDONS
# Paranoid stance - block write access to the sandbox profile
echo "(deny file-write"'*'" (literal \"${processed_template_location}/safari-profile.sb\"))" >>  $IS_ADDONS

if [ ! -f "${IS_DIR}/safari-profile.sb" ];
then
    logger -t sandbox "ERROR: IronSuite/IronSafari - Sandbox file (${IS_DIR}/safari-profile.sb) not found, so we refuse to execute. Exiting"
    echo  "ERROR: IronSuite/IronSafari - Sandbox file (${IS_DIR}/safari-profile.sb) not found, so we refuse to execute. Exiting"
    exit 1
fi

if [ "$IS_DEBUG" = "on" ];
then
    
    # remove the 'with no-log' lines from the rule set
  
    echo "Running in debug mode. File - ${processed_template_location}/safari-profile.sb + friends will be left after execution"

    sed -E -e "s/\(deny\ file\-read\-metadata\ \(with\ no\-log\)\)//g" -e "s/\(with no-log\)//g"  -e "s/%%username%%/${username}/g" -e "s=%%PATH%%=${processed_template_location}/=g" -e "s=%%tmpdir%%=${tmpbase}=" ${IS_DIR}/safari-profile.sb > ${processed_template_location}/safari-profile.sb
else

    # Gracefully remove temp files, both for normal terminations and when terminated. Leave those temp files around if running in debug mode

    trap 'rm -rf "${processed_template_location}" >/dev/null 2>&1' 0
    trap "exit 2" 1 2 3 15

    sed -e "s/%%username%%/${username}/g" -e "s=%%PATH%%=${processed_template_location}/=g" -e "s=%%tmpdir%%=${tmpbase}=" ${IS_DIR}/safari-profile.sb > ${processed_template_location}/safari-profile.sb
fi

# Now build the complete profile file from the parts enabled by options + base rule set.

cat $IS_ADDONS >>  ${processed_template_location}/safari-profile.sb

#
# We copy ALL the plugin files no matter what the config file say
#

sed -e "s/%%username%%/${username}/g" ${IS_DIR}/java.sb > ${processed_template_location}/java.sb
sed -e "s/%%username%%/${username}/g" ${IS_DIR}/citrix.sb > ${processed_template_location}/citrix.sb
sed -e "s/%%username%%/${username}/g" ${IS_DIR}/quicktime.sb > ${processed_template_location}/quicktime.sb

cd ${processed_template_location}

if [ "$IS_DEBUG" = "on" ];
then
    /usr/bin/sandbox-exec -f "${processed_template_location}/safari-profile.sb" "/usr/bin/basename"
    /usr/bin/sandbox-exec -f "${processed_template_location}/safari-profile.sb" "/Applications/Safari.app/Contents/MacOS/safari"
else
    /usr/bin/sandbox-exec -f "${processed_template_location}/safari-profile.sb" "/usr/bin/basename" &> /dev/null
    /usr/bin/sandbox-exec -f "${processed_template_location}/safari-profile.sb" "/Applications/Safari.app/Contents/MacOS/safari" &>/dev/null
fi
