#!/bin/sh
#

init_configfs()
{
    if [ -d "/config.defaults" ]; then
	    # Copy default configs if needed
	    for FILE in `find /config.defaults/* -print | sort`; do
		DEST=/config/${FILE#/config.defaults/}
		if [ -f $FILE -a ! -e ${DEST} ]; then
		    echo copy template file $DEST
		    cp $FILE $DEST
		elif [ -d $FILE -a ! -e ${DEST} ]; then
		    echo create template dir $DEST
		    mkdir -p $DEST
		fi
	    done
    fi
#    tar -k -C /config -vxf /config.defaults.tar
}

init_profilefs()
{
    OVERRIDES="settings.conf"

    if [ -d "/profile/config" ]; then
	    # Check if we should use profile settings
	    for FNAME in $OVERRIDES; do
		FILE=/profile/config/$FNAME
		DEST=/config/$FNAME
		if [ -f $FILE ]; then
		    if [ ! -L "$DEST" ]; then
			rm -f $DEST
		    elif [ "`readlink $DEST`" != "$FILE" ]; then
			rm -f $DEST
		    fi
		    if [ ! -e $DEST ]; then
			echo add profile link $DEST == $FILE
			ln -s $FILE $DEST
		    fi
		elif [ -d $FILE -a ! -e ${DEST} ]; then
		    echo create profile dir $DEST
		    mkdir -p $DEST
		fi
	    done
    fi

    # Check if we should clear dead profile links
    for FNAME in $OVERRIDES; do
	    FILE=/config/$FNAME
	    if [ -L $FILE ]; then
		if [ "`readlink $FILE | grep /profile/config/`" -a ! -e "`readlink $FILE`" ]; then
		    echo clear profile symlink $FILE == `readlink $FILE`
		    rm -f $FILE
		fi
	    fi
    done
}

case "$1" in
    start)
	echo -n "Mounting config fs... "
	
	NFSFS=`cat /proc/cmdline | grep nfsroot= | sed 's/.*nfsroot=\([^ ]*\).*/\1/'`
	PROFILEFS=/dev/`cat /proc/mtd | grep "\"Profile\"" | sed 's/mtd\(.\):.*/mtdblock\1/'`

	# Mount nfs profile fs if present
	if [ "$NFSFS" ]; then
	    mount -t nfs -o nolock,rw $NFSFS.profile /profile
	    init_profilefs
	    echo "done"
	    if [ $? == 0 ]; then
		unset PROFILEFS
	    fi
	fi

	# Mount profile fs if present
	if [ "$PROFILEFS" ]; then
    	    mount -o noatime,rw -t jffs2 $PROFILEFS /profile
	    init_profilefs
	fi

	CONFIGFS=/dev/`cat /proc/mtd | grep "\"Sys-Config\"" | sed 's/mtd\(.\):.*/mtdblock\1/'`

	# Mount nfs config fs if present
	if [ "$NFSFS" ]; then
	    mount -t nfs -o nolock,rw $NFSFS.config /config
	    init_profilefs
	    echo "done"
	    if [ $? == 0 ]; then
		unset CONFIGFS
	    fi
	fi

	# Mount config fs if present
	if [ "$CONFIGFS" ]; then
    	    mount -o noatime,rw -t jffs2 $CONFIGFS /config
	    init_configfs
	fi

	# Clear old debug dumps
	if [ "`du -s /config/debug/ | sed 's/\([0-9]*\).*/\1/'`" -gt "500" ]; then
    	    /usr/sbin/log_persist -- Clear logs over 500k
    	    /bin/rm -f /config/debug/*
	fi

	echo "done"
	;;
    stop)
	echo -n "Unmounting config fs... "

	umount /profile
	umount /config

	echo "done"
	;;
    reconfigure)
	    init_profilefs
	    init_configfs
	;;
    *)
	echo "Usage: $0 {start|stop}"
	exit 1
	;;
esac
