#!/bin/sh

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

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

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

echo "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
    case "$SCRIPT" in
      (*.sh)
        /bin/sh ./$SCRIPT stop
        ;;
      (*)
        ./$SCRIPT stop
        ;;
    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
    case "$SCRIPT" in
      (*.sh)
        /bin/sh ./$SCRIPT start
        ;;
      (*)
        ./$SCRIPT start
        ;;
    esac
  fi
done  

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

echo $PROFILE_CUR" --> "$PROFILE_NEW > $VPN_STATE_FILE
