#!/bin/sh -e

PROG="${0##*/}" #program name

. /etc/sysconfig/i18n

print_version()
{
	cat <<EOF
$PROG version 0.0.1

Written by Stanislav Ievlev

Copyright (C) 2004 ALT Linux Team
EOF
	exit
}

print_usage()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
Usage: $PROG --list <package-list> --destination <destination path>

utility to install base system

Valid options are:
  -h, --help		display help screen
  -v, --version		display version information
  -f, --file-list	list of the packages to install
  -s, --source		source path (were packages lives)
  -d, --destination	destination path
Report bugs to <inger@altlinux.org>
EOF
	[ -n "$1" ] && exit "$1" || exit
}

file_list=
rootdir=
source=

TEMP=`getopt -n $PROG -o h,v,f:,s:,d: -l help,version,file-list:,destination:,source: -- "$@"` || print_usage
eval set -- "$TEMP"

while :; do
	case "$1" in
		-h|--help) print_usage 0
			;;
		-v|--version) print_version
			;;
		-f|--file-list) shift; file_list=$1
			;;
		-d|--destination) shift; rootdir=$1
			;;
		-s|--source) shift; source=$1
			;;
		--) shift; break
			;;
		*) Fatal "unrecognized option: $1"
			;;
	esac
	shift
done

install_langs=${SUPPORTED##.=}

echo "file_list=$file_list"
echo "rootdir=$rootdir"
echo "source=$source"
echo "install_langs=$install_langs"

macros_dir=/etc/rpm

mkdir -p "$macros_dir" ||:
mkdir -p "$rootdir/$macros_dir" ||:
mkdir -p "$rootdir/var/lib/rpm" ||:

macros_file="${macros_dir}/macros"

[ -f $macros_file ] && mv -f $macros_file $macros_file.pr_save

if grep -qs "^%_install_langs" $rootdir/$macros_file 2>/dev/null; then
    subst "s,^%_install_langs.*,%_install_langs $install_langs," $rootdir/$macros_file
else
    echo "%_install_langs $install_langs" >>$rootdir/$macros_file
fi    

cp -f $rootdir/$macros_file $macros_file 

/usr/bin/rpmdb --root=$rootdir --initdb
export DURING_INSTALL=1
cat $file_list |sed "s,.*,$source&,"|xargs rpmi --install -vh --root $rootdir

[ -f $macros_file.pr_save ] && mv -f $macros_file.pr_save $macros_file
