#!/bin/sh
#Install required system files into a common chroot root
#Copyright 2004 -- Gyepi Sam <gyepi@praxis-sw.com>

target_root=$1
datafile=$2

function test_file {
  file=$1
  if ! [ -f $file ]; then
    Usage "Cannot find find file: [$file]."
    return 1
  fi
  return 0 
}

function usage {
  echo $@
  echo "$0: target-root [chroot-data-file]" > /dev/stderr
  exit 1
}

if [ -z "$target_root" ]; then
  usage "target root directory required"
fi

if [ -z "$chroot_files" ]; then
  datfile='chroot-files.dat'
  chroot_file="$(dirname  $0)/$datfile"
fi

test_file $chroot_file || usage "cannot find chroot-data-file"

BINARIES="$(grep -v ^# $chroot_file)"

test -d $target_root || mkdir -p $target_root 

LIBS=`ldd $BINARIES 2> /dev/null | cut -f2 -d\> | cut -f1 -d\( | grep "^ "|sort -u`

for f in $BINARIES $LIBS;do
  if ! [ -f $f ]; then
    echo "source file [$f] not found" > /dev/stderr
    continue
  fi
  install -D "$f" ${target_root}${f}
done
