#!/bin/sh

PROFILE_DIR="/etc/network/profiles"
PROFILE_STATE_FILE="/var/run/network/profile"

#------------------------------------------------------------------------------
# Load the current and new profile

PROFILE_CUR=`cat $PROFILE_STATE_FILE | awk '{print $3}'`
PROFILE_NEW="offline"

echo -n "Switching to profile "$PROFILE_NEW": "

#------------------------------------------------------------------------------
# If the new and current profiles are the same, exit here

[ "$PROFILE_NEW" != "$PROFILE_CUR" ] || exit 0

#------------------------------------------------------------------------------
# Run Stop-Scripts for the current profile

cd $PROFILE_DIR/$PROFILE_CUR/rc.d
for SCRIPT in $(echo K[0-9][0-9]*); do
  if [ -n "$SCRIPT" ]; then
    echo -n "."
    case "$SCRIPT" in
      (*.sh)
        /bin/sh ./$SCRIPT stop &> /dev/null
        ;;
      (*)
        ./$SCRIPT stop &> /dev/null
        ;;
    esac
  fi
done

#------------------------------------------------------------------------------
# Copy all profile specific files for the new profile

cd $PROFILE_DIR/$PROFILE_NEW/files.d
tar cf - . | (cd /; tar xf -)

#------------------------------------------------------------------------------
# Run the Start-Scripts for the new profile

cd $PROFILE_DIR/$PROFILE_NEW/rc.d
for SCRIPT in $(echo S[0-9][0-9]*); do
  if [ -n "$SCRIPT" ]; then
    echo -n "."
    case "$SCRIPT" in
      (*.sh)
        /bin/sh ./$SCRIPT start &> /dev/null
        ;;
      (*)
        ./$SCRIPT start &> /dev/null
        ;;
    esac
  fi
done  

#------------------------------------------------------------------------------
# Save new profile

echo $PROFILE_CUR" --> "$PROFILE_NEW > $PROFILE_STATE_FILE
echo " done."