#!bin/ash

export TMPDIR="/tmp/Intimate.$$"
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$TMPDIR/installer
export PATH=$PATH:util/
MUSICPID=""

sendsig() {
	if [ ".$2" = "." ]; then
		PROG=$1
		SIG=""
	else
		PROG=$2
		SIG=$1
	fi
	pid=`/bin/ps -e |
	/bin/grep $PROG |
        sed -e 's/^  *//' -e 's/ .*//'`
        [ "$pid" != "" ] && kill $SIG $pid
	return $pid
}

# For the fb input/output change
write() {
  echo $*
}

cleanup() {
  write Installer cleaning up...
  if [ ! -z "$MUSICPID" ]; then
    write "killing music ($MUSICPID)"
    sendsig music
  fi

  #gzip -d -c fb.snap.gz > $FBDEVICE && rm fb.snap.gz
#  sendsig -CONT Xipaq
#  xrefresh -display :0.0
  #if [ -x util/xrefresh ]; then util/xrefresh 2>/dev/null ; fi
  if [ -d $TMPDIR/util ]; then rm -rf $TMPDIR/util ; fi
  if [ -d $TMPDIR/pics ]; then rm -rf $TMPDIR/pics ; fi
  if [ -d $TMPDIR/sound ]; then rm -rf $TMPDIR/sound ; fi
  exit 1
}

get_file() {
	if [ -x util/led ]; then util/led 1 0 1 1 ; fi
	FNAME=`basename $1`	
	    write -n "Getting $FNAME ..."
	    wget --quiet http://intimate.handhelds.org/installer/$1
	    if [ $? -ne 0 ];
	    then
        	    write "Failed to wget $FNAME"
		    return 1
	    fi
	    write -n "Checking the md5sum... "
	    wget --quiet http://intimate.handhelds.org/installer/$1.md5sum
	    if [ $? -ne 0 ];
	    then
	            write "Failed to wget the md5sum"
		    if [ -x util/led ]; then util/led 0 0 1 1 ; fi
		    return 1
	    fi
	    VALIDMD5SUM=`cat ${FNAME}.md5sum`
	    OURMD5SUM=`md5sum $FNAME`
	    if [ "$OURMD5SUM" != "$VALIDMD5SUM" ]; then
	        write "BAD... "
	        rm $FNAME ${FNAME}.md5sum
		if [ -x util/led ]; then util/led 0 0 1 1 ; fi
	       	return 1 
	    else
	        write -n "OK... "
	        rm ${FNAME}.md5sum
		mkdir -p `dirname $1`
		odir=`pwd`
		cd `dirname $1`
		tar zxf ${odir}/${FNAME} 2>/dev/null
		rm ${odir}/${FNAME}
		cd ${odir}
		if [ -x util/led ]; then util/led 0 0 1 1 ; fi
		return 0
	    fi
	return 0
}

trap cleanup INT TERM
write

#Check the MD5sum for the isntaller
if [ "."$INTIMATE_NOMD5 = "." ]; then
	write -n "Checking the md5sum for the installer... "
	wget --quiet http://intimate.handhelds.org/installer/installer.md5sum
	if [ $? -ne 0 ]; 
	then 
	        write "Failed to wget the md5sum... exiting"
	        exit 1
	fi
	VALIDMD5SUM=`cat installer.md5sum`
	OURBASENAME=`basename $0`
	OURMD5SUM=`md5sum $OURBASENAME`
	if [ "$OURMD5SUM" != "$VALIDMD5SUM" ]; then
		write "The md5sum of this program is:"
		write "$OURMD5SUM"
		write "The website says the md5sum should be:"
		cat installer.md5sum
	        write "MD5SUM Bad... exiting."
	        rm installer.md5sum
	        exit 1
	else
	        write "OK.. proceeding with install"
	        rm installer.md5sum
	fi
else
	write "Skipping md5 check..."
fi

mkdir $TMPDIR
cd $TMPDIR

# Figure out partition layout (parse /proc/mounts? this'll work for now anyway)
# Its kinda backwards - most common case first.

if [ -f /dev/.devfsd ]; then 
	MTDSEP="/"
else
	MTDSEP=""
fi

#if [ ! -b /dev/mtdblock${MTDSEP}3 -a ! -b /dev/mtdblock${MTDSEP}2 -a -b /dev/mtdblock${MTDSEP}1 ]; then
#	BOOTBLOCK="/dev/mtdblock${MTDSEP}0"
#	ROOTBLOCK="/dev/mtdblock${MTDSEP}1"
#elif [ ! -b /dev/mtdblock${MTDSEP}3 -a -b /dev/mtdblock${MTDSEP}2 ]; then
#	BOOTBLOCK="/dev/mtdblock${MTDSEP}0"
#	PARAMSBLOCK="/dev/mtdblock${MTDSEP}1"
#	ROOTBLOCK="/dev/mtdblock${MTDSEP}2"
#elif [ -b /dev/mtdblock${MTDSEP}3 ]; then
#	BOOTBLOCK="/dev/mtdblock${MTDSEP}0"
#	PARAMSBLOCK="/dev/mtdblock${MTDSEP}1"
#	KERNELBLOCK="/dev/mtdblock${MTDSEP}2"
#	ROOTBLOCK="/dev/mtdblock${MTDSEP}3"
#else
#	write "Your partitions are weird.. bailing!"
#	exit 1
#fi
	
export DISPLAY=:0.0

# Suspend X..
#sendsig -STOP Xipaq

# Save a copy of the framebuffer
#FBDEVICE="/dev/fb${MTDSEP}0"

#gzip > fb.snap.gz < $FBDEVICE

# Display first picture here..
#get_file util/installerfiles.tgz && util/lcd 1 && get_file pics/install_0.pnm.tgz && util/pnmtofb pics/install_0.pnm >/dev/null 2>&1 && util/lcd 0 && rm pics/*pnm
write

# set the date 
write -n "Setting time with ntpdate..."
util/ntpdate -b ntp2.ja.net
write "Done."
write

#Ask about music
MUSIC=""
while [ "$MUSIC" != "y" ]  && [ "$MUSIC" != "n" ];
do
	read -p "Would you like music during the install [Y/n]? " MUSIC
	if [ "$MUSIC" = "" ]; then MUSIC="y" ; fi
done
if [ "$MUSIC" = "y" ] && get_file sound/player.tgz; then
    /tmp/bin/ash ./sound/music &
fi

write
write
write "Intimate can run off of a pcmcia/cf drive, or it can run off of nfs.  If you run off of nfs, the share must already be configured in /etc/fstab as /mnt/nfs."
write
NFSROOT=""
while [ "$NFSROOT" != "y" ] && [ "$NFSROOT" != "n" ]; 
do
	read -p "Would you like to use nfs? [y/N]? " NFSROOT
	if [ "$NFSROOT" = "" ]; then NFSROOT="n"; fi
done

if [ "$NFSROOT" = "y" ]; then
	mount /mnt/nfs
	if [ $(grep /mnt/nfs /proc/mounts |wc -l) -eq 1 ]; then
		export INTIMATEROOT="/mnt/nfs"
	else
		write "Mount of /mnt/nfs failed.  Fix that, then come back here and we can start again."
		exit 1
	fi
else

	#Ask about fdisk

	write
	write
	write "The intimate installer expects /dev/discs/disc0/part2 to be the install partition, and /dev/discs/disc0/part3 to be a swap partition. If your partitions are not correctly configured then the boot procedure for intimate will fail, and you will have to manually configure your linuxrc and fstab."
	write
	RUNFDISK=""
	while [ "$RUNFDISK" != "y" ]  && [ "$RUNFDISK" != "n" ];
	do
		read -p "Would you like run FDISK to partition your drive? [y/N]? " RUNFDISK
		if [ "$RUNFDISK" = "" ]; then RUNFDISK="n" ; fi
	done
	if [ "$RUNFDISK" = "y" ]; then 
		get_file util/fdisk.tgz && util/fdisk /dev/discs/disc0/disc && rm util/fdisk
	fi
	
	write 
	write
	write "The intimate boot process assumes that you will be using a reiserfs filesystem. If you are not, then you will have to manually configure your linuxrc and fstab."
	write
	#Ask about mkreiserfs
	MAKEFILESYSTEM=""
	while [ "$MAKEFILESYSTEM" != "y" ]  && [ "$MAKEFILESYSTEM" != "n" ];
	do
		read -p "Would you like to perform mkreiserfs on /dev/discs/disc0/part2 ? [Y/n]? " MAKEFILESYSTEM
		if [ "$MAKEFILESYSTEM" = "" ]; then MAKEFILESYSTEM="y" ; fi
	done
	if [ "$MAKEFILESYSTEM" = "y" ]; then 
		get_file util/mkreiserfs.tgz && util/mkreiserfs /dev/discs/disc0/part2 && rm util/mkreiserfs
	fi

	#Ask about mkswap
	write
	write
	write "The fstab used on the intimate base images assume that /dev/discs/disc0/part3 will be a swap partition."
	write "The system should boot, even if swap is not correctly configured."
	write
	MAKESWAP=""
	while [ "$MAKESWAP" != "y" ]  && [ "$MAKESWAP" != "n" ];
	do
	        read -p "Would you like to perform mkswap on /dev/discs/disc0/part3 ? [y/n]? " MAKESWAP
	done
	if [ "$MAKESWAP" = "y" ]; then
	        get_file util/mkswap.tgz && util/mkswap /dev/discs/disc0/part3 && rm util/mkswap
	fi
	SWAPON=""
	while [ "$SWAPON" != "y" ] && [ "$SWAPON" != "n" ]; do
		read -p "Would you like to swapon /dev/discs/disc0/part3? [y/N] " SWAPON
	done
	if [ "$SWAPON" = "y" ]; then
		swapon /dev/discs/disc0/part3
	fi
	
	#mount the drive
	write
	write
	write "OK.. going to mount the microdrive on /mnt/intimate..."
	write "Again.. if it's already mounted, you needn't do this bit..."
	write
	MOUNTUDRIVE=""
	while [ "$MOUNTUDRIVE" != "y" ]  && [ "$MOUNTUDRIVE" != "n" ];
	do
		read -p "Would you like to mount /dev/discs/disc0/part2 on /mnt/intimate? [y/n]? " MOUNTUDRIVE
	done
	if [ "$MOUNTUDRIVE" = "y" ]; then 
		mount -t ext3 /dev/discs/disc0/part2 /mnt/intimate
	fi
	if grep -q /mnt/intimate /proc/mounts ; then
		export INTIMATEROOT="/mnt/intimate"
	else
		write "Mount failed.. bailing out."
		exit 1
	fi
fi # NFS or IDE

#rsync the image..
write 
write
write "Excellent.. now we're made it through to the long hard slog... "
write "It's time to rsync the microdrive with the release distro server..."
write "It's a big download.. I wouldn't fancy doing this on a modem... "
write
RSYNCDRIVE=""
while [ "$RSYNCDRIVE" != "y" ]  && [ "$RSYNCDRIVE" != "n" ];
do
	read -p "Would you like to rsync $INTIMATEROOT with the release server? [Y/n]? " RSYNCDRIVE
	if [ "$RSYNCDRIVE" = "" ]; then RSYNCDRIVE="y" ; fi
done
if [ "$RSYNCDRIVE" = "y" ]; then 
#	get_file pics/install_4.pnm.tgz
#	util/pnmtofb pics/install_4.pnm > /dev/null 2>&1 && rm pics/*pnm
	get_file util/rsync.tgz && util/led 1 0 1 1 ; 
	RSYNCDONE=0
	while [ $RSYNCDONE -eq 0 ]; do
		util/rsync -zcurvpl --progress intimate.handhelds.org::intimate-beta $INTIMATEROOT && RSYNCDONE=1
	done
	util/led 0 0 1 1
	 rm util/rsync
	write ; write "Phew... rsync complete :)"
fi

#Install the debian packages we want/need
write
write
write "OK.. now we're going to configure our base, update our package list, and"
write "install a few packages..."
write
POSTINST=""
#read -p "${INTIMATEROOT}" CORROOT
#if [ "$CORROOT" != "y" ]; then exit 1; fi

while [ "$POSTINST" != "y" ]  && [ "$POSTINST" != "n" ];
do
	read -p "Would you like to install .debs ? [Y/n]? " POSTINST
	if [ "$POSTINST" = "" ]; then POSTINST="y" ; fi
done
if [ "$POSTINST" = "y" ]; then 
	mount -t devfs devfs ${INTIMATEROOT}/dev

	#Copy the resolv.conf from familiar
	write "Snarfing /etc/resolv.conf from familiar"
	cp /etc/resolv.conf ${INTIMATEROOT}/etc/resolv.conf

	# Generate some network settings.
	IFACE=`netstat -nr | grep ^0.0.0.0 | util/awk {'print $8'}`
	if [ $IFACE != "ppp0" ] ; then 
		DEFGW=`netstat -nr | grep ^0.0.0.0 | util/awk {'print $2'}`
		ADDR=`ifconfig $IFACE | grep "inet addr" | util/awk {'print $2'} | util/awk -F : {'print $2'}`
		MASK=`ifconfig $IFACE | grep Mask | util/awk {'print $NF'} | util/awk -F : {'print $2'}`
		NETWORK=`netstat -nr | grep $IFACE$ | grep $MASK | util/awk {'print $1'}`
		BROADCAST=`ifconfig $IFACE | grep Bcast: | util/awk {'print $3'} | util/awk -F : {'print $2'}`
		write
		write
		write "# Network settings autodetected by the intimate install process"
		write "auto $IFACE"
		write "iface $IFACE inet static"
		write "          address $ADDR"
		write "          netmask $MASK"
		write "          network $NETWORK"
		if [ $BROADCAST ] ; then 
       	 	write "          broadcast $BROADCAST"
		fi
		write "          gateway $DEFGW"
	
		CONFIGNET=""
		while [ "$CONFIGNET" != "y" ]  && [ "$CONFIGNET" != "n" ];
		do
       		 	read -p "Add the above to /etc/network/interfaces in intimate? [Y/n]" CONFIGNET
		        if [ "$CONFIGNET" = "" ]; then CONFIGNET="y" ; fi
	
		done
		if [ "$CONFIGNET" = "y" ] ; then
			echo >> ${INTIMATEROOT}/etc/network/interfaces
			echo "# Network settings autodetected by the intimate install process" >>${INTIMATEROOT}/etc/network/interfaces
			echo "auto $IFACE" >> ${INTIMATEROOT}/etc/network/interfaces
			echo "iface $IFACE inet static" >> ${INTIMATEROOT}/etc/network/interfaces
			echo "          address $ADDR" >> ${INTIMATEROOT}/etc/network/interfaces
			echo "          netmask $MASK" >> ${INTIMATEROOT}/etc/network/interfaces
			echo "          network $NETWORK" >> ${INTIMATEROOT}/etc/network/interfaces
			if [ $BROADCAST ] ; then 
       			 	echo "          broadcast $BROADCAST" >> ${INTIMATEROOT}/etc/network/interfaces
			fi
		echo "          gateway $DEFGW" >> ${INTIMATEROOT}/etc/network/interfaces
		fi
	fi	

	# Set the timezone within intimate
	${INTIMATEROOT}/usr/sbin/chroot ${INTIMATEROOT}/ tzconfig

	#Copy the lib/modules/ from familiar
	write
	write  "copying /lib/modules/"
	cp -av /lib/modules/* ${INTIMATEROOT}/lib/modules/

	# Get the latest package lists
	write	
	write "Getting the latest package lists..."	
	${INTIMATEROOT}/usr/sbin/chroot ${INTIMATEROOT}/ apt-get update

#	# Bring the base image bang up to date
#	write
#	write "Bringing the base image bang up to date..."
#	/mnt/intimate/usr/sbin/chroot /mnt/intimate/ apt-get dist-upgrade
#	rm /mnt/intimate/var/cache/apt/archives/*.deb

	# Install the menu package.. - Kludge - 2 broken packages later on.
	${INTIMATEROOT}/usr/sbin/chroot ${INTIMATEROOT}/ apt-get install menu
	rm ${INTIMATEROOT}/var/cache/apt/archives/*.deb

	# Install the tools for compiling kernels.
	write
	write "Installing the tools for compiling kernels..."
	${INTIMATEROOT}/usr/sbin/chroot ${INTIMATEROOT}/ apt-get install libncurses5-dev gcc gcc-2.95 make cpp cpp-2.95 binutils libc6-dev
	rm ${INTIMATEROOT}/var/cache/apt/archives/*.deb

	# Install extra command line tools
	write
	write "Installing extra command line tools..."
	${INTIMATEROOT}/usr/sbin/chroot ${INTIMATEROOT}/ apt-get install strace less ncftp ssh2 wget file ntpdate bzip2
	rm ${INTIMATEROOT}/var/cache/apt/archives/*.deb
	
	# Install the X system.
	write
	write "Installing the X system...."
	${INTIMATEROOT}/usr/sbin/chroot ${INTIMATEROOT}/ apt-get install xserver-tiny-h3600 blackbox-ipaq cpu-scale xfonts-scalable-nonfree rxvt xstroke xcalibrate xvkbd
	rm ${INTIMATEROOT}/var/cache/apt/archives/*.deb

	# Install some apps.
	write
	write "Installing some X apps..."
	${INTIMATEROOT}/usr/sbin/chroot ${INTIMATEROOT} apt-get install wmsmixer wmrecord wmmp3 wmapm bubblemon gtktetris mingle
	rm ${INTIMATEROOT}/var/cache/apt/archives/*.deb

	#Finished installing .debs
	write
	write "Finished installing .debs... "

fi


#Install intimateboot and set params..
write
write
write "OK.. onto the final stage.."
write "This is where we install the intimateboot package and set your bootparams correctly"
write
INTIMATEBOOT=""
while [ "$INTIMATEBOOT" != "y" ]  && [ "$INTIMATEBOOT" != "n" ];
do
	read -p "Would you like to install the intimateboot package? [y/n]? " INTIMATEBOOT
done
if [ "$INTIMATEBOOT" = "y" ]; then 
	#Display the intimateboot splashscreen
#	get_file pics/install_2.pnm.tgz
#	util/pnmtofb pics/install_2.pnm >/dev/null 2>&1 && rm pics/*pnm
	get_file util/ipaqbb.tgz && wget -q http://intimate.handhelds.org/installer/intimateboot_0.5-1_arm.ipk && ipkg install ./intimateboot_0.5-1_arm.ipk
	rm intimateboot_0.5-1_arm.ipk

fi

write
write "All done.. shutting down installer"
cleanup
