#!/bin/sh

# $Id: mount_iso.sh,v 1.7 2007/04/26 05:10:31 sjg Exp $

force=

while :
do
    case $1 in
    --force) $NO_FORCE_MOUNT eval force=:; shift;;
    *) break;;
    esac
done

pkgpath=$1
mntpoint=$2
package=$3
pkg=${pkgpath##*/}

#
# SHA1 is much better than MD5, use it if available
#
for hash in sha1 md5
do
    [ -s /sbin/$hash ] || continue
    [ -s $pkgpath.$hash ] || continue

    want=`cat $pkgpath.$hash`
    have=`/sbin/$hash < $pkgpath`
    if [ x$have != x$want ]; then
	logger -t mount_check -s -p daemon.alert "`$hash $pkgpath` != $want"
	$force exit 65		# EX_DATAERR
    fi
    break
done

# make sure we can mount it
[ -d $mntpoint ] || (umask 022; mkdir -p $mntpoint)

mdd=`mdconfig -a -t vnode -o jcompress -o readonly -JO -f $pkgpath`
if [ -z $mdd ]; then
    echo "Unable to mount $package - no more md devices"
    exit 1
fi
if mount -t cd9660 -r /dev/$mdd $mntpoint; then
    echo "Mounted $package package on /dev/$mdd..."
    # load fingerprints if present
    if [ -x /sbin/veriexec -a -s $mntpoint/pkg/manifest ]; then
	/sbin/veriexec -C $mntpoint $mntpoint/pkg/manifest
    fi
    # look to see if this package has a special mount procedure
    postmount=$mntpoint/mount.post

    if [ -f $postmount ]; then
	echo "Executing $postmount.."
	$postmount $mntpoint
	x=$?		# just so it shows up
	case $x in
	0)  ;;		# all ok
	1)  exit 1;;	# failed but carry on
	*)  echo "Unmounting $mntpoint..."
	    umount $mntpoint &&
	    mdconfig -d -u ${mdd##*md}
	    exit $x
	    ;;
	esac
    fi
    exit 0
else
    echo Unable to mount $package on /dev/$mdd
    mdconfig -d -u ${mdd##*md}
    exit 1
fi
