#!/bin/sh
# Args:
# $1 = slackware initrd (*MUST* end with .gz)
# $2 = slamd64 initrd (ditto)

BBVER=1.4.2
CWD=$(pwd)

if [ $(whoami) != "root" ]; then
	echo "You must be root to run this script."
	exit 1
fi

if [ "x$2" = "x" ]; then
	echo "Syntax: $0 slackware-initrd slamd64-initrd"
	exit 2
fi

# Build busybox
if [ ! -d /tmp/busybox-$BBVER/_install ]; then
	sh busybox.SlackBuild
fi

# Build dropbear
if [ ! -d /tmp/pkg-dropbear ]; then
	cd dropbear; sh dropbear.Slackbuild
fi

NEWTREE=$(mktemp -d)
cd $NEWTREE

echo "# Extracting Slackware initrd"
zcat $1 | cpio -i

echo "# Finding modules"
MODULELIST=$(mktemp)
zcat $1 | cpio -t | grep lib/modules | grep -v -- -smp | grep .ko 2>/dev/null >$MODULELIST
KVER=$(head -n 1 $MODULELIST | cut -f3 -d/)

echo "# Updating modules"
rm -rf lib/modules
for file in $(cat $MODULELIST); do	
	mkdir -p $(dirname $file)
	install -oroot -groot -m644 /$file $file
done
depmod -ae -b $PWD

echo "# Replacing busybox and dropbear"
cat /tmp/busybox-$BBVER/_install/bin/busybox > bin/busybox
cat /tmp/pkg-dropbear/bin/dropbearmulti > bin/dropbearmulti

echo "# Replacing 32-bit binaries with 64-bit binaries"
for file in $(find -type f | xargs file | grep "ELF 32" | cut -f1 -d: ); do
	rm $file
	sfile=$(basename $file .bin)
	if echo $file | grep -q '\.so'; then
		# Got a library
		dirs="/lib64 /usr/lib64"
	else
		dirs="/bin /usr/bin /sbin /usr/sbin /usr/libexec /lib64"
	fi
	for dir in $dirs fail; do
		if [ $dir = fail ]; then
			echo "Could not find $file"
			break;
		fi
		if [ -e $dir/$sfile ]; then
			cp $dir/$sfile $file
			break;
		fi
	done
done

echo "# Adding extra libraries"
# Slackware apparently recompiles coreutils to not depend on them; I'm not going to.
for lib in libattr libacl libmagic; do
	grep lib64/$lib*.so /var/log/packages/* | cut -f2 -d: | xargs -ifoo install -oroot -groot -m755 /foo lib/
done

echo "# Installing /etc/magic"
# Needed by 'file'
install -oroot -groot -m644 /etc/magic etc/magic
		
echo "# Cleaning up libraries"
for dir in lib usr/lib; do
	(
		cd $dir
		ln -s lib ../lib64
		find -type l | xargs rm
		ldconfig -n .
	)
done

echo "# Installing SeTPKG"
cat $CWD/SeTPKG > usr/lib/setup/SeTPKG

echo "# Creating new compressed initrd image"
find . | cpio -o -H newc | gzip -9c > $2

rm -rf $NEWTREE $MODULELIST
