#!/bin/bash
#
# MacOSX Sandbox profile for the Adium IM client
#
# 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.
#
#
#

prog=VLC
username=$(whoami)
processed_template_location=$(mktemp -d -t  ${prog}-sandbox)
IV_DIR=`pwd`

IV_CONF=${IV_DIR}/IronVLC.config
IV_ADDONS=${processed_template_location}/ironVLC-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. IronVLC wrapper startup script exiting."
                return 2
                ;;
        esac
}

#
# Preset some var's to default values. NOTE - Change value in the IronVLC.config file
#

IV_DVD=/dev/rdisk1
IV_DOWNDIR=~/Downloads
IV_UPDIR=~/Uploads
IV_MOVIES=~/Movies
IV_DEBUG=off


# Gracefully remove temp files, both for normal terminations and when terminated

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


if [ -f "$IV_CONF" ];
then

    for i in DEBUG LOGGING UPLOAD DOWNLOAD DVD MOVIES
    do

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

	echo "I = $i" 

	j=`cat $IV_CONF | egrep -v '^[ 	]*#'| egrep -v '^$' | grep -i $i | sed 's/[     ]//g' | cut -d# -f1 | cut -d= -f2`
       
	if [ -n "$j" ];
	then
	    echo "Got J = $j" 
	    case $i in
		[Mm][Oo][Vv][Ii][Ee][Ss]) 
		    RDIR=`eval echo "$j"`
		      if [ ! -d  "$RDIR" ];
		      then
			logger -t sandbox "ERROR: IronSuite/IronVLC - The DVD device file configured in config file ($j - $RDIR) does not exist. Exiting"
			echo "ERROR: IronSuite/IronVLC - The The DVD device file configured in config file ($j - $RDIR) does not exist. Exiting"
			exit 1
		      else
			IV_MOVIES="$RDIR"
		      fi
		    ;;
		[Dd][Vv][Dd]) 
		    RDIR=`eval echo "$j"`
		      if [ ! -c  "$RDIR" ];
		      then
			logger -t sandbox "ERROR: IronSuite/IronVLC - The DVD device file configured in config file ($j - $RDIR) does not exist. Exiting"
			echo "ERROR: IronSuite/IronVLC - The The DVD device file configured in config file ($j - $RDIR) does not exist. Exiting"
			exit 1
		      else
			IV_DVD="$RDIR"
		      fi
		    ;;
		    [Dd][Oo][Ww][Nn][Ll][Oo][Aa][Dd])
		    RDIR=`eval echo "$j"`
		      if [ ! -d  "$RDIR" ];
		      then
			logger -t sandbox "ERROR: IronSuite/IronVLC - The download directory configured in config file ($j - $RDIR) does not exist. Exiting"
			echo "ERROR: IronSuite/IronVLC - The download directory configured in config file ($j - $RDIR) does not exist. Exiting"
			exit 1
		      else
			IV_DOWNDIR="$RDIR"
		      fi
		    ;;
		[Uu][Pp][Ll][Oo][Aa][Dd]) RDIR=`eval echo "$j"`
		       if [ ! -d  "$RDIR" ];
		       then
			   logger -t sandbox "ERROR: IronSuite/IronVLC - The upload directory configured in config file ($j) does not exist. Exiting"
			   echo "ERROR: IronSuite - The upload directory configured in config file ($j) does not exist. Exiting"
			   exit 1
		       else
			IV_UPDIR="$RDIR"
		      fi
		    ;;
		[Dd][Ee][Bb][Uu][Gg]|[Ll][Oo][Gg][Gg][Ii][Nn][Gg]) 
		    myyesno "$j"
		    if [ "$?" -eq "0" ];
		    then
			IV_DEBUG="on"
		    fi
		    ;;
		*)  # This should never happen....
		    logger -t sandbox "ERROR: IronSuite/IronVLC - Malformed configure file ($IV_CONF). Keyword  ($i) not supported. Exiting"
		    echo  "ERROR: IronSuite/IronVLC - Malformed configure file ($IV_CONF). Keyword  ($i) not supported. Exiting"
		    exit 1
		    ;;
	    esac

	fi
    done
fi

echo "(allow file-read-data file-read-metadata (subpath \"$IV_MOVIES\"))" >>  $IV_ADDONS
echo "(allow file-read-data file-read-metadata file-ioctl (subpath \"${IV_DVD}\"))" >>  $IV_ADDONS
echo "(allow file-read-data file-read-metadata (subpath \"$IV_UPDIR\"))" >>  $IV_ADDONS
echo "(allow file-read-data file-read-metadata file-write"'*'" (subpath \"$IV_DOWNDIR\"))" >>  $IV_ADDONS
# Paranoid stance - block write access to the sandbox profile
echo "(deny file-write"'*'" (regex \"${processed_template_location}/${prog}."'*'"sb$\"))" >>  $IV_ADDONS



if [ "$IV_DEBUG" = "on" ];
then
    
    # remove the 'with no-log' lines from the rule set
  
    echo "Running in debug mode. File - ${processed_template_location}/${prog}-profile.sb"

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

if [ -e ${IV_DIR}/common-profile.sb ]
then
    sed -e "s/%%username%%/${username}/g" ${IV_DIR}/common-profile.sb > ${processed_template_location}/common-profile.sb
fi


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

cat $IV_ADDONS >>  ${processed_template_location}/${prog}-profile.sb

cd ${processed_template_location}
/usr/bin/sandbox-exec -f "${processed_template_location}/${prog}-profile.sb" "/usr/bin/basename" &> /dev/null
/usr/bin/sandbox-exec -f "${processed_template_location}/${prog}-profile.sb" "/Applications/${prog}.app/Contents/MacOS/${prog}" 
