#!/bin/sh -e
#utility to install rpm package into ramdisk using apt and cpio

if [ "$0" = ./rd_install ]; then
	. ./functions
	lib_dir="$(/bin/pwd)"
else
	. /usr/share/predator/functions
fi

print_usage()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
Usage: $PROG [options] [package]
or: $PROG --ldd [programm]
or: $PROG --filelist <list>

rd_install install files into ramdisk in various ways: as a whole package,
as a separate files, as a result of ldd on file

Valid options are:
  -h, --help	display help screen
  -v, --version	display version information
  -w, --workdir working directory
  -f, --filelist filelist mode: install files listed in filelist
  -l, --ldd	run ldd on file and install all necessary libraries
  -a, --aptconfig	use alternate apt config file
		     				     
Report bugs to <inger@altlinux.org>
EOF
	[ -n "$1" ] && exit "$1" || exit
}


export LC_ALL=C

#parse command line
TEMP=`getopt -n rd_install -o w:,f:,l,v,h,a: -l workdir:,filelist:,ldd,version,help,aptconfig: -- "$@"` || exit 1
eval set -- "$TEMP"

workdir=
filelist=
instlist=
aptconf=
#possible work modes: 0 default, 1 filelist, 2 ldd
mode=0
while :; do
	case "$1" in
		-h|--help) print_usage 0
			;;
		-a|--aptconfig)
			shift
			aptconfig="$1"
			;;
		-w|--workdir)
			shift
			workdir="$1"
		    ;;
		-f|--filelist)
			shift
			filelist="$1"
			mode=1;
		    ;;
		-l|--ldd)
			mode=2
		    ;;
		-v|--version) print_version
		    ;;
		--) shift; break
		   ;;
		*) "unrecognized option: $1"
		    exit 1
			;;
	esac
	shift
done


#calculate list of the packages
[ -z $aptconfig ] && aptconfig=$workdir/aptbox/etc/apt/apt.conf
export APT_CONFIG=$aptconfig

#in filelist mode generate package list from the given filelist
if [ $mode -eq 0 ]
then
    echo "packages mode"
    instlist="$@"
fi
if [ $mode -eq 1 ]
then
    echo "filelist mode"
    indexes=$(get_content_indexes $workdir)
    instlist=$(sort $indexes|join - $filelist | cut -f2 -d' '|sort|uniq)
    echo $instlist
fi
if [ $mode -eq 2 ]
then
    echo "ldd mode"
    instlist=$(ldd $1|sed 's/=>.*//'|grep -v /lib)
fi
packages=$(print_uris $instlist)
echo $packages

#install package contents using cpio
mkdir -p $workdir/ramdisk

if [ $mode -eq 0 ] || [ $mode -eq 2 ]
then
    for i in $packages
    do
    rpm2cpio <$i|(cd $workdir/ramdisk;cpio --quiet --extract --make-directories --sparse)
    done

    #register installed packages in the generic aptbox
    aptbox=$workdir/aptbox
    update_RPM_database $packages
fi
if [ $mode -eq 1 ]
then
    cat $filelist| sed -e 's,^/.*,\.&,' >$workdir/ramdisk/.pattern
    for i in $packages
    do
    rpm2cpio <$i|(cd $workdir/ramdisk;cpio --quiet --extract --make-directories --sparse --pattern-file=./.pattern)
    done
    rm -f $workdir/ramdisk/.pattern
    #don't register files in rpm database in file mode, may be we want other files from this packages in other place
fi
