#!/bin/sh
# Woven together by Curaga (2008)

ROOTFS=`cat /usr/share/doc/tc/release.txt | cut -f1 -d_`

askme(){
dialog --clear --shadow --stdout --title "$2" --inputbox "$1" 0 0
}

fail(){
dialog --msgbox "$1" 0 0
exit 1
}

# Cleansing is important
[ `id -u` != "0" ] && echo "Become root first" && exit 1
rm -rf /netboot
mkdir -p /netboot/pxelinux.cfg

# Say hi
dialog --title "Tiny Core Terminal Server" --clear \
--msgbox "Welcome to the TC Terminal Server!

This box is about to become a
mothership for all your net-booting
computers." 0 0

# Where'd you boot from?
BOOTFROM="$(askme "Give the full path to your boot device
(for example /dev/sda1 or /dev/hdc)

The kernel and rootfs.gz will be copied off it." "Boot device?")"

# Checks & copying to ram
case `cat /proc/mounts` in 
	*$BOOTFROM* )
	true ;;
	* )
	mount $BOOTFROM || exit 1 ;;
esac

PREPATH="$(find /mnt/${BOOTFROM##*/} -name "$ROOTFS".gz)"
AFTERMATH="${PREPATH%/"$ROOTFS".gz}"

[ -n "$PREPATH" ] || fail "Can't find kernel! Aborting!"

cp $AFTERMATH/bzImage /netboot
cp $AFTERMATH/"$ROOTFS".gz /netboot
cp /usr/share/syslinux/pxelinux.0 /netboot

# Ask for da conf: ip, subnet, the deal
STARTIP="$(askme "The first IP address to share?
192.168.0.30 is a good one." "DHCP configuration")"

ENDIP="$(askme "The last IP to share?
192.168.0.60 suggested" "DHCP configuration")"

IFACE="$(askme "The netcard to use?
eth0, for example." "DHCP configuration")"

DNS="$(askme "DNS servers to share?
If you have many, separate with a space" "DHCP configuration")"

SUBNET="$(askme "Subnet of shared IPs?
255.255.255.0 is correct for 192.168..." "DHCP configuration")"

ROUTER="$(askme "Gateway to share?
Most likely the IP of your router." "DHCP configuration")"

KERNOPTIONS="$(askme "Any additional boot options?" "Boot options")"

MYIP=`ifconfig $IFACE | grep inet | cut -d":" -f2 | cut -d" " -f1`

# Now, put those to good use
echo "# The start and end of the IP lease block

start 		$STARTIP
end		$ENDIP

# The interface that udhcpd will use

interface	$IFACE

opt	dns	$DNS
option	subnet	$SUBNET
opt	router	$ROUTER
option	lease	864000		# 10 days of seconds
option	tftp	$MYIP
option	bootfile /netboot/pxelinux.0" > /netboot/udhcpd.conf

# Pxelinux.conf
echo "DEFAULT $ROOTFS
TIMEOUT 300

LABEL $ROOTFS
KERNEL bzImage
APPEND quiet $KERNOPTIONS initrd=$ROOTFS.gz
" > /netboot/pxelinux.cfg/default


# Final check
# A workaround for buggy busybox udhcpd
ln -s /netboot/pxelinux.0 /netboot/pxelinux.0

# If everything's OK, let's roll!
udhcpd /netboot/udhcpd.conf &
echo Please leave this terminal open
udpsvd -E 0 69 tftpd /netboot
