#!/bin/sh

mount -t proc proc /proc
mount -t sysfs sysfs /sys

/bin/busybox --install -s

mdev -s

# /proc/cmdline parser (from Gentoo Wiki)
cmdline() {
    local value
    value=" $(cat /proc/cmdline) "
    value="${value##* $1=}"
    value="${value%% *}"
    [ "$value" != "" ] && echo "$value"
}

# Get some command line options
USER_LOGIN=$(cmdline adlin.login)
USER_PKEY=$(cmdline adlin.key)
USER_IP=$(cmdline adlin.ip)

[ -n "${USER_IP}" ] && echo "${USER_IP}" > /root/my_ip

# Define hostname
hostname adlin-${USER_LOGIN}

# Launch some TTYs
for i in `seq 2 6`
do
    while true
    do
	/usr/bin/setsid /sbin/agetty -l /sbin/fakelogin 38400 "tty${i}" linux
    done &
done

# Hide us!
/bin/rm -f /init /linuxrc

# Randomize time at boot
/bin/date 0$((1 + $RANDOM % 9))0$((1 + $RANDOM % 9))0$((1 + $RANDOM % 9))$((0 + $RANDOM % 6))$((1 + $RANDOM % 9))$((70 + $RANDOM % 30)).$(($RANDOM % 6))$((1 + $RANDOM % 9)) > /dev/null
/sbin/sysctl -w kernel.panic_on_warn=1 > /dev/null
/sbin/sysctl -w net.ipv4.ip_default_ttl=4 > /dev/null

# Launch some daemons
#/usr/bin/setsid /usr/sbin/crond > /dev/null &

# Prepare bonus 2
mkdir -p /mnt

for l in a b c d e f g h i j k l m n o p q r s t u v w x y z zz; do
    [ -b /dev/sd$l ] || break
done

/bin/dd if=/dev/zero of=/dev/sd${l} count=1 > /dev/null 2> /dev/null
/bin/dd if=/dev/zero of=/dev/sd${l}1 count=1 bs=10240000 > /dev/null 2> /dev/null
/sbin/mkfs.ext4 /dev/sd${l}1 > /dev/null 2> /dev/null
mount /dev/sd${l}1 /mnt > /dev/null 2> /dev/null
N1=$((72 - $RANDOM % 35))
N2=$((25 + $RANDOM % 35))
{
    echo -n $N1
    echo -n $N2
    echo -n ${USER_PKEY:$N1:$N2} | sha512sum | cut -d " " -f 1

} > /mnt/bonus2
sync
rm /mnt/bonus2
sync
umount /mnt


# Launch requested init
if grep init= /proc/cmdline > /dev/null 2> /dev/null
then
    INIT=$(cmdline init)
    [ -z "${INIT}" ]

    while true
    do
	sleep $((10 + $RANDOM % 49))
	beep -f 1000 -r 2 -n -r 5 -l 10 --new
    done &

    exec /usr/bin/setsid sh -c "exec '${INIT}' </dev/tty1 >/dev/tty1 2>&1"
else
    while true
    do
	/usr/bin/setsid /sbin/agetty -l /sbin/fakelogin 38400 tty1 linux
    done
fi
