#!/bin/bash
# Script to install INX on a base of the Ubuntu mini.iso 'cli' install.
# set -e

export INX_PPA="deb http://ppa.launchpad.net/inx-devel/ubuntu hardy main"
export INX_SITE=inx.maincontent.net
export INX_SITE_ALT=thoreauputic.boinc.ch
export INX_DIR=buildinx
export INX_EXTRAS="inx-extras"
export SUITE_SCRIPTS=scripts.tar.gz
export NAME="INX 1.17" # edit ad lib

# Are we root?
if [ "$(whoami)" != "root" ] ; then
    echo -e "\nYou need to run $0 as root. Please run sudo $0 .\n"
    exit 1
fi


errorcheck () { if [ $? -ne 0 ] ; then echo -e "\nOops... exiting\n" ; exit 1 ; fi ; }
# Colours in tput format

# Foreground colours

green ()   { tput setaf 2 ; }
yellow ()  { tput setaf 3 ; }
white ()   { tput setaf 7 ; }

bold ()    { tput bold ; }
unbold ()  { tput sgr0 ; bblack ; white ; } #tput sgr0 kills the background - restore

# Background colours

bblack ()   { tput setab 0 ; }
bred ()     { tput setab 1 ; }

bold ; yellow
# See if this makes sense
if grep -q casper /proc/cmdline ; then 
    echo -e "\nThis looks like a live session. It is running using 'casper'.
$0 should be run from a 'command-line only' hard drive install of 'ubuntu-standard',
as the second stage of the 'Netinxtaller'. Exiting...\n"
    unbold ; exit 1
elif ! grep -q 'Ubuntu 8.04' /etc/issue ; then
    echo -e "\nThis doesn't look like an appropriate system to use with $0...\n"
    white
    cat /etc/issue.net
    yellow
    echo -e "\nFor this 'stage 2' script to make sense, we should see 'Ubuntu 8.04'. Exiting...\n"
    unbold ; exit 1
fi

echo -e "\n$(basename $0) installs INX-specific scripts and tweaks to an already installed
'ubuntu-standard' command line install. 

To proceed, hit <enter>. Any other key to quit ...\n"

read -s -n 1 PROCEED
if [ "$PROCEED" != "" ] ; then unbold ; exit ; fi

# Do most of this in /tmp
INXTMP=$(mktemp -d)
cd $INXTMP

# We need the inx-extras tarball from buildinx ...
if ! [ -d "$INX_EXTRAS" ] ; then
        bold ; green
	echo -e "\nChecking site $INX_SITE for needed INX extras...\n" ; sleep 3 
	if ! nc -w 2 -z $INX_SITE 80 ; then
		echo -e "\n$INX_SITE seems to be down ... trying an alternative ...\n" ; sleep 3 
		if nc -w 2 -z $INX_SITE_ALT 80 ; then
			INX_SITE=$INX_SITE_ALT
		else
			echo -e "\nNo luck... $INX_SITE_ALT is down too! Please try again later. Exiting.\n"
			unbold
			exit 1
		fi
	fi
	# Get the tarball of needed extra INX files etc. This only happens once...
	wget --continue -T 5 "$INX_SITE"/"$INX_DIR"/buildinx-extras.tar \
	&& tar xvf buildinx-extras.tar && rm buildinx-extras.tar
	if [ $? -ne 0 ] ; then
	bold ; yellow
	echo -e "\nThere was a problem obtaining the needed extras... Exiting.\n"
	unbold
	exit 1
	fi
fi

# Grab the ppa for sources.list and get the key

echo -e "\n# Autogenerated by $(basename $0)\n" >>  /etc/apt/sources.list
echo "$INX_PPA" >> /etc/apt/sources.list

# This sometimes hangs the script - debug!
bold ; white
apt-key adv --recv-keys --keyserver keyserver.ubuntu.com  89449B3E
unbold
# Update...
apt-get update

# Get the selections list for INX packages ...
# Debug - check on-line status etc.
wget -c http://inx.maincontent.net/updates/selections

# Get rid of the kernel line... we already have a kernel
# We don't need casper either.
egrep -v "(^linux-image|^casper)" selections > newselections

# Grab the lot ...
# Debug - add checks as per buildinx
dpkg --set-selections < newselections
apt-get --no-install-recommends dselect-upgrade

dpkg --configure --pending # vifm issue ...

# OK we have the packages, hopefully ... unpack scripts
bold ; green
echo -e "\n  Unpacking INX-specific scripts...\n"
unbold
sleep 3
tar -C /usr/ -xvzf ./"$INX_EXTRAS"/"$SUITE_SCRIPTS"
source /usr/local/lib/inx/inx_essentials
bold ; green
echo -e "\nUpdating manual page database, please wait, this takes a while...\n"
sleep 4
unbold
mandb -c
bold ; green
echo -e "\nUnpacking INX extras (graphics, video, example content)...\n"
sleep 3
unbold
tar -C /usr/share/ -xvzf ./"$INX_EXTRAS"/graphics.tar.gz ; errorcheck
tar -C /usr/share/ -xvzf ./"$INX_EXTRAS"/video.tar.gz ; errorcheck
tar -C /usr/share/ -xvzf ./"$INX_EXTRAS"/example-content.tar.gz ; errorcheck

bold ; green
echo -e "\nInstalling custom /etc/skel settings...\n" ; sleep 3
unbold
tar -C /etc/ -xvzf ./"$INX_EXTRAS"/etc.skel.tar.gz

# The usbmount config needs additions to recognise and handle FAT usb file systems...
bold ; green
echo -e "\nConfiguring usbmount...\n" ; sleep 2
sed -i 's/FILESYSTEMS="ext2 ext3"/FILESYSTEMS="ext2 ext3 vfat"/g' \
/etc/usbmount/usbmount.conf
sed -i 's/FS_MOUNTOPTIONS=""/FS_MOUNTOPTIONS="-fstype=vfat,gid=floppy,dmask=0007,fmask=0117"/g' \
/etc/usbmount/usbmount.conf

echo -e "General tweaks for themes, media playing, etcetera..." ; sleep 3
		# Add greengold theme for MOC
		cp ./"$INX_EXTRAS"/moc-theme-inx /usr/share/moc/themes/greengold
		# Green theme for irssi...
		mv /usr/share/irssi/themes/default.theme /usr/share/irssi/themes/blue.theme
		cp ./"$INX_EXTRAS"/default.theme /usr/share/irssi/themes/default.theme
		# Switch mplayer to fbdev video, specify full screen by default (fbdev and fs are better in INX)
		sed -i 's/vo=xv/vo=fbdev/g' /etc/mplayer/mplayer.conf
		sed -i 's/#fs=yes/fs=yes/g' /etc/mplayer/mplayer.conf
		
		# Comment out ogg123 line in /etc/mailcap - ogg is not just audio!
		sed -i 's_application/ogg_#application/ogg_g' /etc/mailcap
		echo "application/ogg; playinx '%s'; test=test -z \"\$DISPLAY\"; needsterminal" >> /etc/mailcap
		echo "application/x-ogg; playinx '%s'; test=test -z \"\$DISPLAY\"; needsterminal" >> /etc/mailcap
		
echo '' >> /etc/udev/rules.d/40-permissions.rules
echo 'KERNEL=="mice"                          GROUP="video", MODE="0660"' >> /etc/udev/rules.d/40-permissions.rules
echo 'KERNEL=="tty[0-9]*"                     GROUP="video", MODE="0660"' >> /etc/udev/rules.d/40-permissions.rules
echo 'KERNEL=="fb0"                           GROUP="video", MODE="0660"' >> /etc/udev/rules.d/40-permissions.rules
echo '' >> /etc/udev/rules.d/40-permissions.rules
		
	# Remove contents of these files, which are misleading for inx. Also makes starts a fraction quicker ;)
	> /etc/motd
	> /etc/motd.tail
	# /etc/issue*
	clear > /etc/issue
	echo ""            >> /etc/issue
	echo "$NAME \n \l" >> /etc/issue
	echo "$NAME"       > /etc/issue.net
	
        # Editor and browser defaults..
	    update-alternatives --set editor /usr/bin/jed
	    update-alternatives --set www-browser /usr/bin/elinks
	    
# Alsa is muted by default. This is supposed to work, according to the tldp Howto ...
# There's a -c option for cards, but it works without it, so...
unbold
amixer set Master 80% unmute
amixer set PCM 80% unmute
amixer set CD 80% unmute

# Store that ...
alsactl store


# Change the titles in the update-grub script so our kernel choices will say "INX"...
bold ; green
echo -e "\nSetting INX bootloader titles..." ; sleep 2
unbold

sed -i 's_^title=.*_title=$(cat /etc/issue.net) 2> /dev/null || title="INX"_' /usr/sbin/update-grub
# And update-grub...
bold ; green
echo -e "\nUpdating grub settings for INX ...\n" ; sleep 3
unbold
update-grub -y  > /dev/null 2>&1
bold ; green
	# Edit vga setting in defoptions.
	# Replace defoptions line, removing 'quiet splash' and adding vga=791
	echo -e "\nEnabling framebuffer... " ; sleep 2
		# vga=791 is safer (16 bit) - for example, in qemu this fixes weird colour behaviour.
		sed -i 's/# defoptions=quiet splash/# defoptions=vga=791/g' /boot/grub/menu.lst
		 
	# Pretty colours ;-)
	echo -e "\nSetting up colour bootloader menu.." ; sleep 2
		sed -i 's_#color cyan/blue white/blue_color yellow/green white/green_g' /boot/grub/menu.lst
	# Don't hide the grub menu by default. (default timeout is only 3 seconds)
		sed -i 's/hiddenmenu/#hiddenmenu/g' /boot/grub/menu.lst
		
		
	# We need to re-run update-grub to make this stick - this enables the framebuffer at vga=791 on boot.
	echo -e "\nUpdating framebuffer settings..." ; sleep 2
	update-grub -y > /dev/null 2>&1
	
# Now we need to run the update-inx script (or rather, part of it), to put dot files etc. in place
# Debug - add the bits needed...
#echo -e "\nNow run update-inx\n"
#exit

# Grab /etc/skel and dump into $HOME for first user. New users this happens automatically...
# Check for multiple users (maybe $USER has outsmarted him/her self)

for each in $(ls /home | grep -v lost+found)
  do
    echo -e "\nCopying INX settings to /home/${each} ...\n" ; sleep 2
    cp -r /etc/skel/.[a-zA-Z0-9]* /home/${each}/ #dot files
    cp -r /etc/skel/* /home/${each}/
    chown -R ${each}:${each} /home/${each}/
  done
  
echo -e "\nYou can choose to remove cached packages if you wish. This will save around 245 MB or so
of disc space. Clear the package cache? (default is 'yes' - type n for no, to keep the cache)\n"
read -s -n 1
if ! [ "$REPLY" = "n" -o "$REPLY" = "N" ] ; then
    echo -e "\nOK, clearing cache...\n"
    sleep 2
    apt-get clean
else
    echo -e "\nOK, leaving cached packages in /var/cache/apt/archives. You can clear the cache
with 'sudo apt-get clean' at any time.\n"
    sleep 4
fi

bred ; bold ; yellow  
echo -e "\nThe second stage of your INX install is complete!
You will get better resolution, colours and graphics on reboot. Please hit the <enter> key to proceed."
unbold
echo -e "\n\n\n"
read
shutdown -r now




