#!/bin/bash
##############################################################################
#
#  Copyright (c) 2005, Doremi Labs, Inc.
#    All rights reserved.
#
#  Redistribution in source or binary forms, with or without
#  modification, are NOT permitted.
#
#    Doremi Labs, Inc.
#    1020 Chestnut St.
#    Burbank, CA 91506
#    Tel : (818) 562 1101
#    Fax : (818) 562 1109
#
##############################################################################

USB_LOCK=/doremi/opt/.usb_lock_update
LOG_FILE=/doremi/log/update.log
ETH_CONF=/doremi/sbin/etherconf.out

#
#  log()
#    Display a log on screen and into the log file.
#
log()
{
	echo "[$(date)]: $@" | tee -a $LOG_FILE
}

#
#  die()
#    Log an error then exit
#
die()
{
	log $*
	exit 1
}

#
#  remount_rw()
#    Remount $1 in read write.
# 
remount_rw()
{
	if [ $# -lt 1 ]; then 
		return 22
	fi
	mount -o rw,remount $1
}

#
#  remount_ro()
#    Remount $1 in read only.
# 
remount_ro()
{
	if [ $# -lt 1 ]; then 
		return 22
	fi
	mount -o ro,remount $1
}

#
#  mountperm()
#    Return the mount point $1 permission ('ro' or 'rw').
# 
mountperm()
{
	if [ $# -lt 1 ]; then 
		return 22
	fi
	mount | grep "$1" | grep -q \(ro,
	if [ $? -eq 0 ]; then
		echo -n "ro"
	else
		echo -n "rw"
	fi
}

#
#  generate_report()
#    Generate a report and store it into $1 (path).
# 
generate_report()
{
	if [ $# -lt 1 ]; then 
		return 22
	fi
	test -x /doremi/sbin/report.sh  || return 1
	test -x /doremi/bin/drminfo.out || return 1
 	# pattern: 'report_<serial>_<date>_<time>.tgz'
	local _date=$( date +%m%d%Y )
	local _time=$( date +%H%M%S )
	local _serl=$( /doremi/bin/drminfo.out -c -sn )
	local _name=report_${_serl}_${_date}_${_time}.tgz

	/doremi/sbin/report.sh -o $1/${_name} > /dev/null 2>&1 
}

#
#  do_install()
#    Call `install' and check return value.
#    Die if it returns an error code.
#
do_install()
{
	install $*
	if [ $? -ne 0 ]; then
		die "Failed to: install $*."
	fi
}

#
#  import_ifconfig()
#    Import interface configuration $1 (path).
#    NOTE: make sure the fs is mounted in rw.
#	$1 - configuration file
#	$2 - boolean (0|1) to save configuration file on disk
# 
import_ifconfig()
{
	if [ $# -lt 2 ]; then 
		return 22
	fi
	test -x $ETH_CONF || die "$ETH_CONF is missing."
	local config=$1
	local dosave=$2
	# parse it!
	( cat ${config} ; echo ) |
	(
	# init some default values
	local _face="eth0"
	local _addr=""
	local _mask=""
	local _gate=""
	while read line
	do
		echo ${line} | grep -q '^[ ]*#'
		if [ $? -eq 0 ]; then
			# skip comment
			continue;
		fi
		local _name=$(  echo ${line} | awk '{print $1}' | sed -e 's/[:=]$//g' | tr '[:upper:]' '[:lower:]' | tr -d '[:cntrl:]' )
		local _value=$( echo ${line} | awk '{print $2}' | tr '[:upper:]' '[:lower:]' | tr -d '[:cntrl:]' )
		case "${_name}" in
			interface)
				_face=${_value}
				;;
			ip)
				_addr=${_value}
				;;
			mask|netmask)
				_mask=${_value}
				;;
			gateway)
				_gate=${_value}
				;;
			*)
				;;
		esac
	done
	# save configuration	
	local _cmd="${ETH_CONF} -m -i /etc/network/interfaces ${_face}"
	if [ "${_addr}" = "dhcp" ]; then
		# DHCP
		_cmd=$( echo "${_cmd}" "--address=dhcp" )
	else
		# static
		if [ "${_addr}" != "" ]; then
			_cmd=$( echo "${_cmd}" "--address=${_addr}" )
		fi
		if [ "${_mask}" != "" ]; then
			_cmd=$( echo "${_cmd}" "--netmask=${_mask}" )
		fi
		if [ "${_gate}" != "" ]; then
			_cmd=$( echo "${_cmd}" "--gateway=${_gate}" )
		fi
	fi
	local _out=/tmp/.interfaces.$$.tmp
	eval ${_cmd} > ${_out}
	if [ $? -ne 0 ]; then
		log "Could not create interfaces file ${_out}."
		return
	fi
	# r/w access required
	remount_rw /
	if [ ${dosave} -eq 1 ]; then 
		do_install -m 0644 -o root -g root -D ${_out} /etc/network/interfaces
	fi
	cat "${_out}"
	# apply configuratino
	/sbin/ifdown ${_face} > /dev/null 2>&1 || true
	/sbin/ifup -i "${_out}" ${_face}
        if [ $? -ne 0 ]; then
            echo "error: /sbin/ifup command failed."
        fi
	rm -f "${_out}"
	# back to r/o
	remount_ro /
	)
}

if [ "$UM_MOUNTPOINT" = "" ]; then
	# EINVAL
	exit 22
fi

# To enable if we add automatic package installation (S430) 
if [ -e "$USB_LOCK" ]; then
	# nothing to do, update already applied
	exit 0
fi

#
# if "/doremi/report" exists on USB device, then
# we automatically generates a report and stores it.
#
if [ -e "$UM_MOUNTPOINT/doremi/report" ]; then
	log "Automatically generate a report"
	# r/w access required 	
	_perm=$( mountperm $UM_MOUNTPOINT )
	if [ "$_perm" = "ro" ]; then
		remount_rw $UM_MOUNTPOINT
	fi
	generate_report "$UM_MOUNTPOINT/doremi/report"
	# r/o access
	if [ "$_perm" = "ro" ]; then
		remount_ro $UM_MOUNTPOINT
	fi
	touch $USB_LOCK
fi

#
# if "/doremi/update" exists on USB device, then
# we automatically update network configuration.
#
if [ -d "$UM_MOUNTPOINT/doremi/update/network" ]; then
	# DNS
	if [ -e "$UM_MOUNTPOINT/doremi/update/network/dns" ]; then
		log "Automatically update DNS servers configuration"
		# r/w access required
		remount_rw /
		do_install -m 0644 -o root -g root "$UM_MOUNTPOINT/doremi/update/network/dns" /var/resolv.conf
		dos2unix /var/resolv.conf
		ln -sf   /var/resolv.conf /etc/resolv.conf
		# r/o access
		remount_ro /
	elif [ -e "$UM_MOUNTPOINT/doremi/update/network/dns.txt" ]; then
		log "Automatically update DNS servers configuration"
		# r/w access required
		remount_rw /
		do_install -m 0644 -o root -g root "$UM_MOUNTPOINT/doremi/update/network/dns.txt" /var/resolv.conf
		dos2unix /var/resolv.conf
		ln -sf   /var/resolv.conf /etc/resolv.conf
		# r/o access
		remount_ro /
	fi
	# NTP servers
	if [ -e "$UM_MOUNTPOINT/doremi/update/network/ntp" ]; then
		log "Automatically update NTP servers configuration"
		do_install -m 0644 -o root -g admin "$UM_MOUNTPOINT/doremi/update/network/ntp" /doremi/etc/ntpservers
		dos2unix /doremi/etc/ntpservers
	elif [ -e "$UM_MOUNTPOINT/doremi/update/network/ntp.txt" ]; then
		log "Automatically update NTP servers configuration"
		do_install -m 0644 -o root -g admin "$UM_MOUNTPOINT/doremi/update/network/ntp.txt" /doremi/etc/ntpservers
		dos2unix /doremi/etc/ntpservers
	fi
	# ifconfig
	if [ -e "$UM_MOUNTPOINT/doremi/update/network/ifconfig" ]; then
		log "Automatically update network configuration"
		import_ifconfig "$UM_MOUNTPOINT/doremi/update/network/ifconfig" 1
	elif [ -e "$UM_MOUNTPOINT/doremi/update/network/ifconfig.txt" ]; then
		log "Automatically update network configuration"
		import_ifconfig "$UM_MOUNTPOINT/doremi/update/network/ifconfig.txt" 1
	fi
	# extra ifconfig file in case we want to update multiple interface in one time
	for ((i=0; i<=9; i++)); do
		extra="$UM_MOUNTPOINT/doremi/update/network/ifconfig.$i"
		if [ -e "${extra}" ]; then
			log "Automatically update network configuration"
			import_ifconfig "${extra}" 1
		elif [ -e "${extra}.txt" ]; then
			log "Automatically update network configuration"
			import_ifconfig "${extra}.txt" 1
		else
			break
		fi
	done
	touch $USB_LOCK
fi

#
# if "/doremi/tmp" exists on USB device, then
# we automatically set network configuration.
# IMPORTANT: No change is saved on disk.
#
if [ -d "$UM_MOUNTPOINT/doremi/tmp/network" ]; then
	# ifconfig
	if [ -e "$UM_MOUNTPOINT/doremi/tmp/network/ifconfig" ]; then
		log "Automatically set network configuration"
		import_ifconfig "$UM_MOUNTPOINT/doremi/tmp/network/ifconfig" 0
	elif [ -e "$UM_MOUNTPOINT/doremi/tmp/network/ifconfig.txt" ]; then
		log "Automatically set network configuration"
		import_ifconfig "$UM_MOUNTPOINT/doremi/tmp/network/ifconfig.txt" 0
	fi
	# extra ifconfig file in case we want to set multiple interface in one time
	for ((i=0; i<=9; i++)); do
		extra="$UM_MOUNTPOINT/doremi/tmp/network/ifconfig.$i"
    if [ -e "${extra}" ]; then
      log "Automatically set network configuration"
      import_ifconfig "${extra}" 0
    elif [ -e "${extra}.txt" ]; then
      log "Automatically set network configuration"
      import_ifconfig "${extra}.txt" 0
    else
      break;
    fi
	done
fi

#
# if "/doremi/update" exists on USB device, then
# we search for update packages.
#
if [ -d "$UM_MOUNTPOINT/doremi/update" ]; then
	if [ -n "$(ls $UM_MOUNTPOINT/doremi/update/*.pk[gzx] 2>/dev/null)" ]; then
		for package in $UM_MOUNTPOINT/doremi/update/*.pk[gzx]; do
			base_filename=$(basename "$package")
			log "Automatically schedule installation of $package"
			cp "$package" "/doremi/tmp/${base_filename}"
			mv "/doremi/tmp/${base_filename}" /doremi/etc/rc.once/
		done
	fi
	touch $USB_LOCK
fi
