#!/bin/sh

#Script to change the contents of ~/.ssh/config
#depending whether I'm at home or at work



rename_file(){
	mv $CONFIG_FILE"_temp" $CONFIG_FILE
}

log_port_change(){
	logger -p local0.notice -i -t ssh-config "Ssh's default port for git.frusfrusfrus.net changed to $1"
}

# The start subroutine
config_ssh_port() {
	INTERFACE="en1"

	IP=`ifconfig $INTERFACE | grep "[^ ]inet[^0-9]" | awk '{ print $2 }' - `
	
	#Local network check
	echo $IP | grep "192\.168\.[0-9]\+\.[0-9]\+" > /dev/null
	[[ $? != 0 ]] && exit

	#Token is the third group on a ip address, i.e. XXX.XXX.this_is_token.XXX
	TOKEN=`echo $IP | awk 'BEGIN {FS="."} { print $3}' -`

	CONFIG_FILE=~/.ssh/config

	# My home network is on range 192.168.2.x and work's range is 192.168.0.x
	if [[ $TOKEN -eq 0 ]] ; then
		sed 's/2280/22/g' $CONFIG_FILE > $CONFIG_FILE"_temp" && rename_file && log_port_change "22"
	else
		sed 's/22$/2280/g' $CONFIG_FILE > $CONFIG_FILE"_temp" && rename_file && log_port_change "2280"
	fi
}

. /etc/rc.common
CheckForNetwork 
if [ "${NETWORKUP}" = "-NO-" ]; then exit 0; fi

config_ssh_port

