#!/bin/sh
#---------------------------------------------------------------
# Project         : Mandrake Linux
# Module          : netprofile
# File            : set-netprofile
# Version         : $Id: set-netprofile,v 1.7 2003/09/12 16:13:50 flepied Exp $
# Author          : Frederic Lepied
# Created On      : Fri Mar 21 21:33:06 2003
#---------------------------------------------------------------

TOP=${TOP=/etc/netprofile}

#DBG=-v

# assume cwd is /etc/init.d
stop() {
    for s in $1; do
	if [[ ! -f "$SERVICES/$s" ]]; then
	    [[ -x $s ]] || continue
	    [[ -e /var/lock/subsys/$s ]] || continue
	    grep -q chkconfig $s || continue
	    echo $(egrep -a '^#.*chkconfig: ' $s|awk '{print $5}') $s
	fi
    done | sort -n | cut -d" " -f2
}

# assume cwd is /etc/init.d
start() {
    for s in $2; do
	[[ -x "$s" ]] || continue
	[[ ! -e /var/lock/subsys/"$s" ]] || continue
	grep -q chkconfig $s || continue
	echo $(egrep -a '^#.*chkconfig: ' $s|awk '{print $4}') $s
    done | sort -n | cut -d" " -f2    
}

restoreprofile() {
    while read w; do
	for s in `ls $FILES/$w 2> /dev/null`; do
	    if [[ -r $s ]]; then
		f=$(echo $s | sed "s@$FILES@@")
		mkdir $DBG -p `dirname $f`
		cp $DBG -p "$s" "$f"
	    fi
	done
    done < $TOP/list

    OLD=`LC_ALL=C chkconfig --list | grep -v 'xinetd based services' | cut -f1`
    
    echo $OLD | xargs -n 1 chkconfig --del

    cd "$SERVICES"

    NEW=$(ls)
    
    echo $NEW | xargs -n 1 chkconfig --add
    
    # if we are on a running system, stop and start services
    if [[ -f /var/run/runlevel.dir ]]; then
	cd /etc/init.d
	
	for s in $(stop "$OLD" "$NEW"); do
	    /etc/init.d/$s stop
	done
	
	unset HOSTNAME
	[[ -r /etc/sysconfig/network ]] && . /etc/sysconfig/network
	[[ -n "$HOSTNAME" ]] && hostname $HOSTNAME

	/etc/init.d/network restart

	for s in $(start "$OLD" "$NEW"); do
	    /etc/init.d/$s start
	done
    fi
}

if [[ $# -gt 1 ]]; then
    echo "usage: `basename $0` <profile>" 1>&2
    exit 1
fi

NEWPROFILE="$1"

if [[ -z "$NEWPROFILE" ]]; then
    # Check the kernel command line, profile are selectable
    # right from the boot manager
    eval `cat /proc/cmdline | tr ' ' '\n' | grep PROFILE`
    NEWPROFILE="$PROFILE"
fi

PROFILE=default

if [[ -r $TOP/current ]]; then
    eval `cat $TOP/current`
fi

if [[ "$NEWPROFILE" == "$PROFILE" || -z "$NEWPROFILE" ]]; then
    exit 0
fi

if [[ ! -d $TOP/profiles/"$NEWPROFILE"/files ]]; then
    echo "`basename $0`: unknown profile $NEWPROFILE" 1>&2
    exit 1
fi

save-netprofile "$PROFILE" 1

FILES="$TOP/profiles/$NEWPROFILE/files"
SERVICES="$TOP/profiles/$NEWPROFILE/services"

restoreprofile

echo "PROFILE=\"$NEWPROFILE\"" > $TOP/current

# set-netprofile ends here
