#!/bin/sh -e

HOSTNAME="$1"
if [ -z "$HOSTNAME" ]; then
    HOSTNAME="wine-box"
fi

cleanup() {
    rm -rf "$tmp"
}

trap cleanup EXIT
tmp="$(mktemp -d)"

# 1. Setup runlevels
mkdir -p "$tmp"/etc/runlevels/default
mkdir -p "$tmp"/etc/runlevels/boot
mkdir -p "$tmp"/etc/runlevels/sysinit

# 2. Add services
ln -s /etc/init.d/udev "$tmp"/etc/runlevels/sysinit/udev
ln -s /etc/init.d/networking "$tmp"/etc/runlevels/boot/networking

# 3. AUTO-LOGIN AND AUTO-START X11
# We tell the system to log in root automatically on tty1
mkdir -p "$tmp"/etc/init.d
echo 'ln -s /etc/init.d/agetty /etc/init.d/agetty.tty1'
mkdir -p "$tmp"/etc/conf.d
echo 'agetty_options="--autologin root --noclear"' > "$tmp"/etc/conf.d/agetty.tty1

# 4. Create the script that starts Wine when X starts
mkdir -p "$tmp"/root
cat > "$tmp"/root/.xinitrc <<EOF
#!/bin/sh
# Start the Wine desktop environment
exec wine explorer /desktop=win,1024x768 explorer.exe
EOF
chmod +x "$tmp"/root/.xinitrc

# 5. Start X automatically when root logs in
echo 'if [ -z "$DISPLAY" ] && [ "$(tty)" = "/dev/tty1" ]; then startx; fi' >> "$tmp"/root/.profile

# Set hostname and finish
echo "$HOSTNAME" > "$tmp"/etc/hostname
tar -C "$tmp" -cZ . > "$HOSTNAME.apkovl.tar.gz"

