#!/bin/sh

# connect by synergy to the desktop machine.
# Everybody gets DHCP addresses so we have to 
# find the right system to connect to.  And since
# this laptop is out in the world sometimes it
# doesn't run sshd.

# So, start one ssh connection that both creates
# a tunnel back here for synergy, and starts
# synergyc on the desktop machine.

# Don Marti <dmarti@zgp.org>

### stuff to configure

DESKTOP=00:21:9b:17:d4:e8 # desktop's MAC address

OFFICE_ROUTER=00:1c:f0:c5:ad:d9
  # or any MAC address at the same place

### end stuff to configure


# options for start-stop-daemon
START_OPTS='--start --background --make-pidfile'

# convert a dotted quad to a decimal, for pinging ranges: 
#   http://zgp.org/~dmarti/tips/dotted-quad-to-int/ 
dq2int(){
    a=0
    for b in $(echo $1 | tr . ' '); do
        a=$((256*$a+$b))
    done
    echo $a
}

stopit(){
    start-stop-daemon --stop --oknodo \
      --pidfile ~/.pidfiles/ssh-synergy &> /dev/null
    start-stop-daemon --stop --oknodo \
      --pidfile ~/.pidfiles/synergys &> /dev/null
}

if [ "x$MODE" == "xstop" ]; then
    stopit
elif interface=$(arp -n | grep $OFFICE_ROUTER | \
             awk '{print $5}'); then
    my_ip=$(ifconfig $interface | egrep -o 'inet addr:[^[:space:]]+' | \
      cut -d : -f 2)
    netmask=$(ifconfig $interface | egrep -o 'Mask:[^[:space:]]+' | \
      cut -d : -f 2)
    network=$(dq2int $(ipcalc -nb $my_ip $netmask | \
      grep ^Network | egrep -o '[[:digit:]\.]{3,}'))
    broadcast=$(dq2int $(ipcalc -nb $my_ip $netmask | \
      grep ^Broadcast | egrep -o '[[:digit:]\.]{3,}'))

    # fill the ARP cache -- any better way to do this?
    for addr in $(seq $network $broadcast); do
       ping -w 1 $addr &> /dev/null &
    done

    DESKTOP=$(arp -n | grep $DESKTOP | cut -d ' ' -f 1)
    if [ -z $DESKTOP ]; then
        echo "fail: can't find desktop." 1>&2
        stopit
        exit 2
    fi

    # only start synergy if desktop machine is found and
    # responding to ssh
    # echo "found desktop machine at $DESKTOP"
    if ssh $DESKTOP /bin/true &> /dev/null; then
        # start the Synergy server on lo only
        start-stop-daemon $START_OPTS \
          --pidfile ~/.pidfiles/synergys \
          --exec /usr/bin/synergys -- -f -a 127.0.0.1 
        start-stop-daemon $START_OPTS \
          --pidfile ~/.pidfiles/ssh-synergy \
          --exec /usr/bin/ssh -- \
            -o ServerAliveInterval=1 \
            -R 24800:localhost:24800 \
            $DESKTOP synergyc -f localhost
    else
        echo "fail: can't ssh to desktop at $DESKTOP." 1>&2
        stopit 
        exit 3
    fi
fi
