#!/bin/bash
# undo some XO specific changes done by OOB while creating the image

ISXO=`[ -f /proc/device-tree/mfg-data/MN ] && echo 1 || echo 0`
FIX_RPMS="sed libidn grep which util-linux wget gnupg2 groff gnash"
LOG=/home/olpc/xs-setup.log
FEDORA=`rpm -q fedora-release|gawk 'BEGIN {FS="-";}{print $3}'`
XSARCH=`uname -i`
NO_REBOOT=0
TEXTMODEFLAG="/home/olpc/.textmode"
DEFAULT_SET="-x"
set $DEFAULT_SET

# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
    echo "This script must be run as root" 1>&2
    exit 1
fi

if [ $ISXO = "1" ]
then
    # What kind of XO is this?
    XOTYPE=
    if [ -f /proc/device-tree/mfg-data/M# ];then 
	model=`cat /proc/device-tree/mfg-data/M#` 
        case $model in
        "CL1" | "CL1A")
            XOTYPE="XO1"
            ;;
         "CL1B" | "CL1C")
            XOTYPE="XO1.5"
            ;;
         "CL2" | "CL2A")
            XOTYPE="XO1.75"
            ;;
         "CL4" | "CL4A" | "CL4B" | "CL4C")
            XOTYPE="XO4"
            ;;
         *)
            XOTYPE=
            ;;
         esac
    fi
    export XOTYPE

    if [ "$XOTYPE" = "XO1" ]; then
        if [ ! -f "$TEXTMODEFLAG" ]; then
            set +x
            echo ""
            echo "######################################################"
            echo ""
            echo ""
            echo "The XO-1 needs to use memory that is normally used by the GUI"
            echo "to install XSCE software. Hit return to restart the install process"
            echo "and then re-issue the 'bootstrap-xo' terminal command (up arrow)" 
            echo "" 
            echo "" 
            echo "#####################################################" 
            echo "" 
            read -p "Press [Enter] key to restart the install process" 
            echo "" 
            echo ""
            echo "Going into text mode in 5 seconds"
            #
            # Disable the graphical mode for the XO, diable X11, use memory for serving
            rm /etc/systemd/system/default.target  # remove the link
            ln -sf /lib/systemd/system/multi-user.target /etc/systemd/system/default.target
            touch $TEXTMODEFLAG    
            sleep 5
            telinit 3
#       observation is that changing run levels terminates this script
        fi
        #if [
    fi
    set "$DEFAULT_SET"


    # there are files open in the tempfs /var/log -- so we cannot just unmount it
    # we need to disable tempfs and then start up again on a /var/log directory
    # that persists
    err=`cat /etc/fstab | grep -e "#varlog"`
    if [ "x$err" = "x" ]; then
        while [ $# -gt 0 ]; do
	    case $1 in
		--no-reboot) NO_REBOOT=1 ;;
		(--) shift; break;;
		(-*) echo "$0: error - unrecognized option $1" >&2; exit 1;;
	        (*) break;;

    esac
	    shift
        done

	echo "bootstrap-xo routine started" | tee -a $LOG
	date  2>&1 | tee -a $LOG
	# use the supplied 10-olpc-net.rules remove the 70-olpc-net.rules
	if [ -e /usr/lib/udev/rules.d/70-olpc-net.rules ]; then
	    rm /usr/lib/udev/rules.d/70-olpc-net.rules
	fi

        # NM plugin need to be specified for it to manage deveces
        echo "plugins=keyfile" >> /etc/NetworkManager/NetworkManager.conf

        cat << EOF > /etc/NetworkManager/system-connections/"Sugar Modem Connection"

[connection]
id=Sugar Modem Connection
uuid=62be9bcb7a3d3929fc01d82e038c42f93b339334
type=gsm
autoconnect=false

[ppp]
lcp-echo-failure=5
lcp-echo-interval=30

[ipv4]
method=auto
ignore-auto-dns=true

[serial]
baud=115200

[gsm]
number=*99#
EOF

        chmod 0600 /etc/NetworkManager/system-connections/"Sugar Modem Connection"

	# servers should not sleep
	touch /etc/powerd/flags/inhibit-suspend

	# keep yum cache
	sed -i -e  's/keepcache=0/keepcache=1/' /etc/yum.conf

	# disable "su" without password on the XO
	sed -i -e '6s/^auth/#auth/' /etc/pam.d/su

	# copy .bashrc to /root
	cp -p /home/olpc/.bashrc /root

        # stateless linux rwtab file creates tmpfs that is too small installs
        sed -i -e '/^RW_OPTIONS/ c\
        RW_OPTIONS="-o size=4M -o nr_inodes=2048"' /etc/sysconfig/readonly-root
        sed -i -e '/^empty.*\/var\/lib\/dhcpd/ d' /etc/rwtab

	# Keep docs when installing packages
	sed -i -e  's/%_excludedocs 1/%_excludedocs 0/' /etc/rpm/macros.imgcreate

        yum_cmd="yum -y"

        usbkey=""
        for parts in `ls /dev/sd*1`; do
            if [ x$parts != 'x' ];then
                maybe=`ls -la /sys/class/block/ | grep usb | gawk '{print 9}'`
                if ! [ -z "$maybe" ];then
                    usbkey=`findmnt -n -o TARGET -S $parts`
		    if [ ! -d "$usbkey"/xs-repo/  -a ! -d "$usbkey"/library ];then
			mkdir "$usbkey"/xs-repo			
		    fi
		    echo "INFO using <usbkey>/xs-repo for yum cache" | tee -a $LOG
		    mount --bind "$usbkey"/xs-repo /var/cache/yum
		    # ensures $XSARCH/$FEDORA on fresh usbkey
		    # update the online metadata from previous runs
		    # and confirms available repos
		    $yum_cmd repolist

		    # convert uname -i to match what yum uses
		    if [ $XSARCH = "armv7l" ];then
			XSARCH=armhfp
		    fi
		    # confirm we have a repo to use
		    if [ -d /var/cache/yum/$XSARCH/$FEDORA/repodata ];then
			# the sub-directories hold online-repo cache
			# we use the top level to hold the offline repo 
			# sum of all the cached rpms held
			yum_cmd="yum -c /tmp/yum.conf -y"
			cat << EOF > /tmp/yum.conf

[main]
# this is inside yum where basearch releasever are detected.
cachedir=/var/cache/yum/\$basearch/\$releasever
logfile=/home/olpc/yum.log
keepcache=1
exactarch=1
obsoletes=1
gpgcheck=0
installonly_limit=3

#yum.repos.d=/tmp

#  This is the default, if you make this bigger yum won't see if the metadata
# is newer on the remote and so you'll "gain" the bandwidth of not having to
# download the new metadata and "pay" for it by yum not having correct
# information.
#  It is esp. important, to have correct metadata, for distributions like
# Fedora which don't keep old packages around. If you don't like this checking
# interupting your command line usage, it's much better to have something
# manually check the metadata once an hour (yum-updatesd will do this).
# metadata_expire=90m

# PUT YOUR REPOS HERE OR IN separate files named file.repo
# in /etc/yum.repos.d

[usb-media]
name=usb-media
baseurl=file://"$usbkey"/xs-repo/\$basearch/\$releasever
enabled=1
gpgcheck=0
cost=100

EOF
			echo "FOUND /var/cache/yum/$XSARCH/$FEDORA/metadata" | tee -a $LOG
		    else
			echo "INFO repo metadata not found - skipping repo use" | tee -a $LOG
		    fi
		else
		    echo "INFO no usbkey to use - skipping"
		fi
	    fi
	done

	$yum_cmd install man-pages man-db man 2>&1 | tee -a $LOG

	# re-install these packages to pickup missing docs
	$yum_cmd reinstall $FIX_RPMS 2>&1 | tee -a $LOG

	# install xs-config
	$yum_cmd install xs-config 2>&1 | tee -a $LOG

	# fix usbmount as /media is on tmpfs use /mnt instead
	mkdir -p /mnt/usb0
	mkdir -p /mnt/usb1
	mkdir -p /mnt/usb2
	mkdir -p /mnt/usb3
	mkdir -p /mnt/usb4
	mkdir -p /mnt/usb5
	mkdir -p /mnt/usb6
	mkdir -p /mnt/usb7
        sed -i -e 's:media:mnt:g' /etc/usbmount/usbmount.conf

        # check for other schoolservers on the local network
        tryname="schoolserver"
        if [[ `avahi-browse -t _workstation._tcp | grep schoolserver` ]]; then
            x=1
            tryname="schoolserver.$x"
            while [ $x -le 9 ]; do
                if [[ ! `avahi-browse -t _workstation._tcp | grep "$tryname"` ]]; then
                    break
                fi
                x=$(( "$x" + 1 ))
                tryname="schoolserver.$x"
            done
        else
            echo "no otherschoolservers found"
        fi
      
	# Rename the XO to be schoolserver.local
	sed -i -e '/HOSTNAME=xo/d' /etc/sysconfig/network
	echo $tryname.local > /etc/hostname
	echo "HOSTNAME=$tryname.local" >> /etc/sysconfig/network
        sed -i -e 's:NM_IGNORE_HOSTNAME_LOCALHOST=yes:NM_IGNORE_HOSTNAME_LOCALHOST=no:' /etc/sysconfig/network

	# XO release 12.1.0 makes /var/log  a tempfs -- server logs should persist
	sed -i -e 's:vartmp:#vartmp:' /etc/fstab
	sed -i -e 's:varlog:#varlog:' /etc/fstab

        # Disable the graphical mode for the XO, diable X11, use memory for serving
        rm /etc/systemd/system/default.target  # remove the link
        ln -sf /lib/systemd/system/multi-user.target /etc/systemd/system/default.target

	if [ -e /var/log/yum.log ];then
	    cp /var/log/yum.log /home/olpc/
	fi
	echo "bootstrap-xo routine completed" | tee -a $LOG
	date  2>&1 | tee -a $LOG
	if [ $NO_REBOOT -eq 1 ]; then
	    echo "no-reboot used on cmdline " | tee -a $LOG
	    exit 0
	fi

        set +x
        echo
        echo "================================================================="
        echo "The setup program must reboot before additional setup can proceed"
        echo "The XO will reboot in 'text mode', with white letters on a dark screen"
	echo "Next step is to run 'xs-setup' when rebooted"
        echo "================================================================="
        echo
	read -p "Press [Enter] key to reboot"
	echo "rebooting in 5 seconds"
	sleep 5
	reboot
    else
        echo "This part of the configuration is already completed"
        echo "Next step is to run 'xs-setup'"
    fi
else
    echo "Not an XO please run 'xs-config'"
fi
