#!/bin/sh
### SimpleHTTPServer helper script v0.1 ###

port="80"
interface1="usb0"
interface2="wlan0"
interface3="gprs0"
hostname="`cat /etc/hostname`"

# there's probably better ways to check the IP address, but here we go
ip=`/sbin/ifconfig | grep -A1 $interface1 | awk '/inet addr/ { split($2, x, /:/); print x[2]; }'`
if [ -z "$ip" ]
then
	ip=`/sbin/ifconfig | grep -A1 $interface2 | awk '/inet addr/ { split($2, x, /:/); print x[2]; }'`
	if [ -z "$ip" ]
	then
		ip=`/sbin/ifconfig | grep -A1 $interface3 | awk '/inet addr/ { split($2, x, /:/); print x[2]; }'`
		if [ -z "$ip" ]
		then
			ip="N/A"
			echo -e "No IP address found.\n\n(This could mean that the device is not connected to network or that the network interface in use isn't defined in the script. Server will still run though.)\n"
		fi
	fi
fi

# help text and launching the server
if [ -z $1 ] || [ $1 == "--help" ]
then
	echo -e "Usage: `basename $0` [PATH]"
	echo -e "Share a directory using python's SimpleHTTPServer."
else
	if [ ! -d "$1" ]
	then
		echo "Directory $1 not found"
	else
		cd $1
		echo -e "Sharing $PWD on $hostname, IP address: $ip, port: $port"
		echo -e "(Use Ctrl+c to quit. Otherwise the server will not be killed.)\n"
		develsh -c "python -m SimpleHTTPServer $port > /dev/null"
	fi
fi
exit
