#!/bin/sh
#-*-sh-*-

#
# Copyright © 2009 CNRS
# Copyright © 2009-2010 INRIA
# Copyright © 2009-2010 Université Bordeaux 1
# See COPYING in top-level directory.
#

abs_top_builddir="@abs_top_builddir@"
prefix="@prefix@"
exec_prefix="@exec_prefix@"
bindir="@bindir@"
# this will be changed into $bindir/lstopo during make install
lstopo="$abs_top_builddir/utils/lstopo"

error()
{
    echo $@ 2>&1
}

usage()
{
  echo "$0 <savepath>"
  echo "  Saves the Linux topology files (/sys, /proc, ...) under <savepath>.tar.bz2"
  echo "  and the corresponding lstopo verbose output under <savepath>.output"
  echo "  Example $0 /tmp/\$(uname -n)"
}

ARG=`getopt -o 'h' --long 'help' -n $0 -- $@`
if [ $? -ne 0 ]; then
    usage
    exit 1
fi

eval set -- "${ARG}"
while true
do
    case $1 in
	-h|--help)		usage; exit 1;;
	--)			shift; break;;
    esac
	shift;
done

name="$1"
if [ -z "$name" ] ; then
  usage
  exit -1
fi
basename=`basename "$name"`
dirname=`dirname "$name"`

if ! mkdir -p "$dirname" ; then
    error "Failed to create directory $dirname."
    exit 1
fi

if [ ! -w  "$dirname" ] ; then 
    echo "$dirname is not writable."
    usage
    exit 1
fi
destdir=`mktemp -d`

# Get all files from the given path (either a file or a directory)
# ignore errors since some files may be missing, and some may be
# Restricted to root (but we don't need them).
# Use cat so that we properly get proc/sys files even if their
# file length is wrong
savepath() {
  local dest="$1"
  local path="$2"
  # gather all directories, including empty ones
  find "$path" -type d 2>/dev/null | while read dir ; do	\
    mkdir -p "$dest/$dir" 2>/dev/null ;		\
  done
  # gather all files now
  find "$path" -type f 2>/dev/null | while read file ; do	\
    mkdir -p "$dest/"`dirname $file` ;		\
    cat "$file" > "$dest/$file" 2>/dev/null ;	\
  done
}

# Gather the following list of files and directories
cat << EOF | while read path ; do savepath "$destdir/$basename" "$path" ; done
/sys/devices/system/cpu/
/sys/devices/system/node/
/sys/class/dmi/id/
/sys/kernel/mm/hugepages/
/proc/cpuinfo
/proc/meminfo
/proc/stat
/proc/device-tree/cpus
EOF

# Create the archive and keep the tree in /tmp for testing
( cd "$destdir/" && tar cfj "$basename.tar.bz2" "$basename" )
mv "$destdir/$basename.tar.bz2" "$dirname/$basename.tar.bz2"
echo "Hierarchy gathered in $dirname/$basename.tar.bz2 and kept in $destdir/$basename/"

# Generate the output as well
if [ ! -x "$lstopo" ]
then
    error "Could not find lstopo executable in the install or build dir."
    exit 1
fi
# we need "Topology not from this system" in the output so as to make test-topology.sh happy
export HWLOC_THISSYSTEM=0
"$lstopo" - -v > "$dirname/$basename.output"
echo "Expected topology output stored in $dirname/$basename.output"

exit 0
