#!/bin/bash
 
#----------------------------------------------------------------------------
# calvados_bin_exec - Script to call calvados binaries 
#                   
# April 2015, Helios Tsoi
#
# Copyright (c) 2015 by Cisco Systems, Inc.
# All rights reserved.
#----------------------------------------------------------------------------

# Description : This is a utility to execute the calvados binaries from host
#               os. We would first mount the calvaods required partition 
#               and folder then we would execute it along with .so binaries
#               needed to run the executable 
# Usage :
# calvados_bin_exec <Calvados-mount-point> <prog-path>
#
# NOTE : This script below is a generic script and can be used to call any 
#        calvados related binaries
# 

# Current USage is done by the follow binaries:
# 1.  NO usage 
# 

set -e
CAL_PART=$1; shift
CAL_EXE=$1;  shift

if [ -d "${CAL_PART}" ]; then
    MNT_DIR=${CAL_PART}
else
    part=${CAL_PART##*:}
    dev=${CAL_PART%:*}
    [ "$part" = "$dev" ] && part=1
    partline=$(fdisk -u -l $dev | grep -E "${dev}${part:+(p|)$part} " | tr -d \* | head -1)
    if [ -n "$partline" ]; then
       read name start end blocks_etc <<< "$partline"
       offset=$(($start * 512))
       size=$((($end - $start + 1) * 512))
    fi
    MNT_OPT=ro${offset:+,offset=$offset}${size:+,sizelimit=$size}
    MNT_DIR=$(mktemp -d /tmp/TMP_CAL.XXXXX)
    mount -o ${MNT_OPT}        $dev $MNT_DIR 2>/dev/null || \
    mount -o ${MNT_OPT},noload $dev $MNT_DIR
fi

if [ -h "$MNT_DIR/opt/cisco/calvados/$CAL_EXE" ]; then
   export LD_LIBRARY_PATH=$(ls -l ${MNT_DIR}/opt/cisco/calvados/usr/lib*/* | grep -- '->' | sed "s,.*-> \(.*\)/[^/]*$,${MNT_DIR}\1," | sort -u | tr \\n :).
   EXE=${MNT_DIR}`readlink $MNT_DIR/opt/cisco/calvados/$CAL_EXE`
   "$EXE" "$@"
else
   echo "$CAL_EXE": Command not found >&2
fi

if [ ! -d "${CAL_PART}" ]; then
    umount $MNT_DIR
    rmdir $MNT_DIR
fi


