#!/bin/bash

# this script will integrate numa infrastructure support into the xen-unstable
# tree. 

function main() {

   LINUX_TARBALL=${1:-"linux-2.6.16.tar.bz2"}
   XEN_UNSTABLE_TARBALL=${2:-"xen-unstable-src.tgz"}
   XEN_NUMA_PATCH=${3:-"patches/convert_linux_to_xen_numa.patch"}
   RAW_COPY_LIST=${4:-"copylist"}
   NEWLINE="
";
   OIFS="${IFS}";


   [ -r ${LINUX_TARBALL} ] || {
      echo "Linux tarball missing, acquiring..."
      $(set -x; wget -q http://ftp.kernel.org/pub/linux/kernel/v2.6/${LINUX_TARBALL})
   }

   [ -r ${XEN_UNSTABLE_TARBALL} ] || {
      echo "couldn't find Xen unstable tarball, acquiring..."
      $(set -x; wget -q http://www.cl.cam.ac.uk/Research/SRG/netos/xen/downloads/xen-unstable-src.tgz);
   }

   [ -r ${XEN_NUMA_PATCH} ] || {
      echo "Xen numa integration patch missing:"
      echo "it should have come with this script."
      return 1;
   }
   
   [ -r ${RAW_COPY_LIST} ] || {
      echo "Files to copy from Linux into Xen sparse tree missing:"
      echo "it should have come with this script.";
      return 1;
   }

   echo "unpacking Xen-unstable, pristene copy"
   rm -rf a/
   tar -xzf xen-unstable-src.tgz
   mv xen-unstable a

   echo "unpacking Xen-unstable, copy to modify"
   rm -rf xen-unstable
   tar -xzf xen-unstable-src.tgz
   # dir will be renamed at end

   # unpack linux tarball
   echo "unpacking linux tarball"
   local kdir=${LINUX_TARBALL%.tar.*}
   # assuming bz2 ext.
   [ ! -d ${kdir} ] && tar xjf ${LINUX_TARBALL}

   echo "copying unmodified source into tree..."

   local -a rawcopy=( `cat ${RAW_COPY_LIST} | sed -e "s,%KDIR%,${kdir},g" -e "s,%XEN%,xen-unstable,g"` )
   echo "rawcopy=${rawcopy[@]}";
   echo "size=${#rawcopy[@]}";
   local i=""
   local j=""
   for ((i=0; i<${#rawcopy[@]}; i=i+2)); do 
      j=$((${i}+1)); 
      cp -a ${rawcopy[${i}]} ${rawcopy[${j}]};
      echo "cp -a ${rawcopy[${i}]} ${rawcopy[${j}]}";
   done

#   exit

   # apply integration patch
   pushd xen-unstable &>/dev/null
   set -x;
   patch -s -p1 < ../${XEN_NUMA_PATCH}
   set +x;
   popd &>/dev/null

#   exit

   # clean up the rejects and orig files
   find xen-unstable -type f -name '*.rej' -o -name '*.orig' | xargs rm -f

   local output="xen_numa_01_infrastructure.patch"
   echo "Creating ${output}..."
   mv xen-unstable b
   diff -urN a b > ${output}
   echo "Wrote ${output}" 
   return 0;
}

main "$@"
exit $?
