#! /bin/sh

# Copyright (c) 2007-2008 by Marc Feeley, All Rights Reserved.

# ***WARNING***
#
# This shell program is very platform specific.  It will be hard to
# get working on another development machine. The program launches
# Windows on my development machine, an intel based MacOS X computer,
# using Parallels workstation.  The shell program's argument is a
# script which is transferred to the Windows virtual PC and executed
# by a MSYS/MinGW shell.  The output from this shell is then
# transferred back.  All transfers are done with scp, which is setup
# to not require a password.

rm -f /tmp/_windows-rsh*
cp "$1" /tmp/_windows-rsh-script

self_id_addr=""

for intf in en1 en0; do #for intf in `ifconfig -l -u`; do
  intf_ip_addr=`ifconfig $intf | sed -e "s/.*inet [^0-9]*\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\).*/\1/p" -e "d"`
  if test "$intf_ip_addr" != "" -a "$intf_ip_addr" != "127.0.0.1"; then
    self_ip_addr="$intf_ip_addr"
  fi
done

ORIGINATOR_IP="$self_ip_addr"

#ORIGINATOR_HN="`hostname`"
#ORIGINATOR_IP="`dig +tries=2 +time=2 +short $ORIGINATOR_HN`"
#if [ "$?" != "0" -o "$ORIGINATOR_IP" == "" ] ; then
#  ORIGINATOR_IP="192.168.0.5" # Usual static IP address of development machine
#fi

ORIGINATOR="`id -nu`@$ORIGINATOR_IP"

echo "c:/msys/1.0/bin/sh --login -c \"sleep 15;export ORIGINATOR=$ORIGINATOR;rm -rf /tmp/windows-rsh*;scp $ORIGINATOR:/tmp/_windows-rsh-script /tmp/windows-rsh-script;chmod +x /tmp/windows-rsh-script;/tmp/windows-rsh-script < /dev/null > /tmp/windows-rsh-script.out 2>&1;scp /tmp/windows-rsh-script.out $ORIGINATOR:/tmp/_windows-rsh-script.out;rm -rf /tmp/windows-rsh*;shutdown -s -f -t 0\"" > /tmp/_windows-rsh.tmp

# Updated for Parallels workstation 4.0
windows_pvm="$HOME/Library/Parallels/winxp.pvm"
ifloppy="`dirname $0`/blank-floppy.fdd"
ofloppy="$windows_pvm/winxp-auto.fdd"

rm -f "$ofloppy"
dd conv=notrunc if="$ifloppy" of="$ofloppy" bs=512 seek=0 count=2880 2> /dev/null
dd conv=notrunc if=/dev/zero of="$ofloppy" bs=512 seek=33 count=32 2> /dev/null
dd conv=notrunc if=/dev/zero of="$ofloppy" bs=512 seek=65 count=32 2> /dev/null
dd conv=notrunc if=/tmp/_windows-rsh.tmp of="$ofloppy" bs=512 seek=33 2> /dev/null

open "$windows_pvm/config.pvs"

while [ ! -e /tmp/_windows-rsh-script.out ] ; do
  sleep 1
done

sleep 60 # wait for Windows to shutdown (this is about 10 seconds more than needed on a 2GHz MacBook Pro)

rm -f "$ofloppy"

if [ -e /tmp/_windows-rsh-script.out ] ; then
  cat /tmp/_windows-rsh-script.out
fi

rm -f /tmp/_windows-rsh*
