# contains utility function useful during the provisioning of the image
#
# author : jd_jedi@users.sourceforge.net
#

## PREREQUISITE : PLEASE source defs.sh
# TODO : add, info, warning , and error level to the log file
log_msg()
{
    msg="$*"
    
    
    if [ -n "${log_file}" ]; then
        echo $msg >> ${log_file}
#    else
        echo $msg
    fi
}



#
# fetch file given http or ftp url
#
# --- usage --
# SRC="http://www.google.com"
# DEST="/tmp/google_home"
# fetch_file $SRC $DEST
# 
#

fetch_file()
{
  src=$1
  dest=$2
  if [ -e $dest ]; then
      log_msg "$dest already exists"
  else
     tmp_http=`echo $src | $SED -n "/http:\\/\\//p"`
     tmp_ftp=`echo $src | $SED -n "/ftp:\\/\\//p"`

     if [ "$tmp_http" = "$src" ]; then
	 python -c "import urllib, shutil; urllib.urlretrieve($qt$src$qt,$qt$dest$qt)"
     elif [ "$tmp_ftp" = "$src" ]; then
	 python -c "import urllib, shutil; urllib.urlretrieve($qt$src$qt,$qt$dest$qt)"
     else 
 	 $CP -a $src $dest
     fi
  fi
}


#
# Create file based disk or LVM volume
# 
# usage
#    create_disk disk_type disk_name disk_size 
#
#    disk_type : file or VBD or phy or LVM
#    disk_size : in MB
#

create_disk()
{
   dk_type=$1
   dk_name=$2
   dk_size=$3

   echo "create_disk $dk_type, $dk_name, $dk_size"

   # create disk
   MB=M
   if [ $dk_type = "LVM" -o $dk_type = "phy" ]; then
      # adjust the lvm name (remove leading /dev)
      dk_name=`echo $dk_name|$SED "s/^\/dev\///"`
      dk_lvm_group=`echo $dk_name |$SED "s/^\\(.*\)\\/\\(.*\\)/\1/"`
      log_msg $dk_name, $dk_lvm_group

      $LVDISPLAY $dk_lvm_group/$dk_name >& /dev/zero
      if [ "$?" = "0" ]; then
         # volume exists, remove it.
	 $LVREMOVE -f $dk_lvm_group/$dk_name >& /dev/zero
      fi
      $LVCREATE -L $dk_size$MB -n $dk_name $dk_lvm_group
      if [ "$?" != "0" ]; then
	 log_msg "Error creating LVM $dk_name $dk_lvm_group"
	 exit 1
      fi
   elif [ $dk_type = "VBD" -o $dk_type = "file" ]; then
      $DD if=/dev/zero of=$dk_name bs=1 seek=$dk_size$MB count=1  >& /dev/zero
      if [ "$?" != "0" ]; then
	 log_msg "Error creating VBD $dk_name"
	 exit 1
      fi
   fi


   if [ "$?" != "0" ]; then
      log_msg "Error creating disk " $dk_name $d_type 
      exit 1 
   else
      log_msg "Disk created." $dk_name, $dk_type
   fi

}

function source_python_config()
{
    conf_file=$1

    temp_config=`$MKTEMP`
    python <<EOF > $temp_config
import types
g={}
l={}
execfile("$1",g,l); 
vtypes = [ types.StringType,
               types.ListType,
               types.IntType,
               types.FloatType]
for (k, v) in l.items():
    if type(v) in vtypes:
        if type(v) == types.ListType:
           print '%s="%s"' % (k,v)
        else:
           print '%s="%s"' % (k,v)
EOF
    if [ -e $temp_config ]; then
	source $temp_config
    fi
    rm $temp_config
    unset temp_config
    unset conf_file
}
