#!/bin/csh

if ( "" == "$2" ) then
  echo "Usage: installworld <target_directory> <package> [package ...]"
  echo 'Environment variables:'
  echo '$APTCONFDIR - apt configuration to copy (default: /etc/apt)'
  exit 1
endif

set target="$1"
shift

if ( ! -d "$target" ) then
  echo "Target directory doesn't exist"
  exit 1
endif

if ( ! ${?APTCONFDIR} ) then
  setenv APTCONFDIR /etc/apt
endif

set start_time=`date '+%F %T'`
echo "$start_time Running installworld to $target ..."

# wipe the target directory, but keep the lost+found/
( cd "$target" && rm -rf `ls-F -A | sed -re 's,lost\+found/?,,g'` )

umask 022
mkdir -p "$target/etc/apt" \
  "$target/var/cache/apt/archives/partial" \
  "$target/var/lib/apt/lists/partial"
rpmdb --root "$target" --initdb
rsync -ax "$APTCONFDIR/" "$target/etc/apt/"

set APTOPTIONS="-o RPM::RootDir=$target -o Debug::pkgMarkInstall=true -o Debug::pkgProblemResolver=true -o APT::Install::Virtual=true -o APT::Install::VirtualVersion=true -o Dir::State=$target/var/lib/apt/ -o Dir::Cache=$target/var/cache/apt/ -o Dir::Etc::SourceList=$target/etc/apt/sources.list"
apt-get $APTOPTIONS update
apt-get $APTOPTIONS -y install $*

# Give RPM some time for database update
echo "Cleaning up APT data..."
find "$target/var/cache/apt" -type f -delete
find "$target/var/lib/apt" -type f -delete
sync
sleep 5

set stop_time=`date '+%F %T'`
echo "$stop_time Finished installworld to $target ..."
echo "Time used: $start_time - $stop_time"
