#!/bin/sh

source /lib/rc/sh/functions.sh
mkdir -p /modules/

TMPDIR="/tmp/rootfs-$$"

# PKG=$1

DEPS=`emerge -pv $1`
PKG=`echo ${DEPS} | grep -e ".*/.*" | sed -e 's/.*] //g' -e 's/ .*//g'`

[[ -z $1 ]] && eerror "Nothing to emerge!" && exit 1

einfo "Here are the dependencies :"
echo "${DEPS}"

read -p "Proceed with the merging? [y]/n " ASK

if [ "${ASK}" == "n" ]; then
	exit 0
fi

einfo "Preparing to merge all required packages"
for x in $PKG
do
	emerge -1b ="${x}"
	mkdir -p "${TMPDIR}"
	[[ ! -e /usr/portage/packages/"${x}".tbz2 ]] && eerror "Build failed" && exit 1
	tar -jxf /usr/portage/packages/"${x}".tbz2 -C "${TMPDIR}"
	mkdir -p "${TMPDIR}"/var/db/pkg/"${x}"
	cp -a /var/db/pkg/"${x}"/* "${TMPDIR}"/var/db/pkg/"${x}"/
	MOFILE=`echo $x | sed -e 's/.*\///g'`
	einfo "Building module for $MOFILE"
	mksquashfs "${TMPDIR}" /modules/"${MOFILE}".lzm -b 1048576 -comp lzma
	einfo "Module now available in /modules/$MOFILE.lzm"
	rm -rf "${TMPDIR}"
done

einfo "Finished creating modules."
einfo "You can now copy your modules from /modules/*.lzm to"
einfo "your usb stick or whatever your modules support is."

