#!/bin/bash
# TUN_SHARING. Enables OS X to Share Internet Connection over a tunneled
# interface like tun0 from OpenVPM.
#   
#   Copyright (C) 2009  Christoph Schaal <scytale@tleilaxu.de>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>

#   $Id: tun_sharing.sh 22 2010-01-09 09:12:24Z christoph $


## Check if we are root
if [ `whoami` != "root" ] ; then
        echo "You must be root to run this script!"
        exit 1
fi


## Read parameters from command line
if test $# -ne 2; then
        echo "Usage: $0 <wan-if> <tun-if>";
        exit 2
fi
wanif=$1
tunif=$2


## Fetch infos
natdpid=`cat /var/run/natd.pid`
tunip=`ifconfig tun0 | grep inet | cut -f 2 -d " "`
ipfwrule=`ipfw list | grep "divert 8668" | cut -f 1 -d " "`


## Restart natd
kill $natdpid
sleep 10
/usr/sbin/natd -alias_address $tunip \
    -interface $wanif \
    -use_sockets -same_ports -unregistered_only -dynamic -clamp_mss -enable_natportmap \
    -natportmap_interface $tunif

 
## Set firewall properly
ipfw del ipfwrule
ipfw add divert natd ip from any to any via $tunif > /dev/null


## done :)
echo "If you don't see any errors above we are done:"
echo "Sharing tunneled interface $tunif on local interface."
exit 0

