File wisotool of Package wine-lol

#!/bin/sh
# Quick and dirty script to install apps from .iso files
# Adapted from winetricks as of r995
# Copyright 2007, 2008, 2009, 2010 Google (Dan Kegel, dank@kegel.com)
# Copyright 2008, 2009, 2010 Austin English (austinenglish@gmail.com)
# License: LGPL (for compatibility with winehq)
# Please report problems at http://code.google.com/p/winezeug/issues
# Note to contributors: please avoid gnu extensions in this shell script,
# as it has to run on MacOSX and Solaris, too.  A good book on the topic is
# "Portable Shell Programming" by Bruce Blinn

#---- Constants -------------------------------------------------

# Name of this version of wisotool (YYYYMMDD)
VERSION=20100731

early_wine()
{
    WINEDLLOVERRIDES=mshtml= $WINE "$@"
}

# Default values for important settings if not already in environment.
# These settings should not need editing here.
case "$OS" in
 "Windows_NT")
    # Cheezy fix for getting rid of double slashes when running cygwin in wine
    case "$HOME" in
      /) HOME="" ;;
    esac
    WINE=""
    WINESERVER=true
    WINEPREFIX="${WINEPREFIX:-$HOME/.wine}"
    DRIVE_C="C:/"
    XXXPATH=cygpath
    ;;
 *)
    WINE=${WINE:-wine}
    WINEVERSION=`$WINE --version`
    WINESERVER=${WINESERVER:-wineserver}
    WINEPREFIX="${WINEPREFIX:-$HOME/.wine}"
    DRIVE_C="$WINEPREFIX/dosdevices/c:"
    XXXPATH="early_wine winepath"
    # FIXME: does id work on mac/solaris?
    USERID=`id -u`
    ;;
esac

WISOTOOL_DIR=${WISOTOOL_DIR:-$HOME/.wisotool}

# You can add your own verb to wisotool by creating $WISOTOOL_VERBS/foo.verb
WISOTOOL_VERBS="${WISOTOOL_VERBS:-$WISOTOOL_DIR/verbs}"
mkdir -p "$WISOTOOL_VERBS"

# Postinstall scripts, if any, go here
WISOTOOL_POST="${WISOTOOL_POST:-$WISOTOOL_DIR/postinstall}"

# Internal variables; these locations are not too important
WISOTOOL_CACHE="${WISOTOOL_CACHE:-$HOME/.wisotoolcache}"
test -d "$WISOTOOL_CACHE" || WISOTOOL_CACHE="$WISOTOOL_DIR/cache"
WISOTOOL_CACHE_WIN="`$XXXPATH -w $WISOTOOL_CACHE | tr '\012' ' ' | sed 's/ $//'`"
WISOTOOL_TMP="$DRIVE_C"/wisotooltmp
WISOTOOL_TMP_WIN='c:\wisotooltmp'

# Clean up after failed runs, if needed
rm -rf "$WISOTOOL_TMP"
mkdir -p "$WISOTOOL_TMP"

# Handle case where z: doesn't exist
case "$WISOTOOL_CACHE_WIN" in
""|*\?\\unix*)
    # WISOTOOL_CACHE isn't accessible via a drive letter mapping, so make one,
    # but be sure to clean it up later.
    for letter in y x w v u t s r q
    do
        if ! test -d "$WINEPREFIX"/dosdevices/${letter}:
        then
            WISOTOOL_CACHE_SYMLINK="$WINEPREFIX"/dosdevices/${letter}:
            ln -sf "$WISOTOOL_CACHE" "$WISOTOOL_CACHE_SYMLINK"
            break
        fi
    done
    ;;
esac

USERNAME=${USERNAME:-$LOGNAME}

# Overridden for windows
ISO_MOUNT_ROOT=/mnt/wisotool
ISO_MOUNT_LETTER=i

WINDIR="$DRIVE_C/windows"

#---- Functions -------------------------------------------------

# Detect which sudo to use
detect_sudo() {
    SUDO=sudo
    test "$GUI" = 1 || return
    if test x"$DISPLAY" != x""
    then
        if test -x "`which gksudo 2>/dev/null`"
        then
            SUDO=gksudo
        elif test -x "`which kdesudo 2>/dev/null`"
        then
            SUDO=kdesudo
        fi
    fi
}

# Detect which menu program to use
detect_menu() {
    # TODO: add 'dialog'
    MENU=xmessage
    if test -x "`which zenity 2>/dev/null`"
    then
        MENU=zenity
    elif test -x "`which kdialog 2>/dev/null`"
    then
        MENU=kdialog
    fi
}

warn() {
    echo "------------------------------------------------------"
    echo "$@"
    echo "------------------------------------------------------"

    test "$GUI" = 1 || return

    # For some reason, nulls were showing up in $@?!, causing truncated output in zenity
    msg="`echo $@ | tr '\000' ' '`"
    case $MENU in
    *zenity) zenity --error --title=Wisotool --text="$msg" --no-wrap;;
    *kdialog) kdialog --title Wisotool --error "$msg" ;;
    *xmessage) xmessage -title Wisotool -center "  Error: $msg  " ;;
    esac
}

die() {
    warn "$@"

    exit 1
}

# Abort if user doesn't own the given directory (or its parent, if it doesn't exist yet)
die_if_user_not_dirowner() {
    if test -d "$1"
    then
        checkdir="$1"
    else
        # fixme: quoting problem?
        checkdir=`dirname "$1"`
    fi
    nuser=`id -u`
    nowner=`ls -l -n -d -L "$checkdir" | awk '{print $3}'`
    if test x$nuser != x$nowner
    then
        die "You (`id -un`) don't own $checkdir. Don't run wisotool as another user!"
    fi
}

#----------------------------------------------------------------

usage() {
    set +x
    # WARNING: do not use single quote in any package description; that breaks the gui menu.
    echo "Script to install games automatically."
    echo "Usage: $0 [options] package [package] ..."
    echo ""
    echo "Options:"
    echo " -q         quieter"
    echo " -v         verbose"
    echo " -V         display Version"
    echo "Packages:"
    sort "$WISOTOOL_TMP"/menutext
    echo "Pseudopackages:"
    echo " load          Load a disc into the iso cache"
    echo " load=KEY      Load a disc with given key; only works from commandline at moment"

    # Show the other help message, too
    case $GUI in
    0) load_help ;;
    esac
}

#----------------------------------------------------------------
# Trivial GUI just to handle case where user tries running without commandline

kdialog_showmenu() {
    title="$1"
    shift
    text="$1"
    shift
    col1name="$1"
    shift
    col2name="$1"
    shift
    while test $# -gt 0
    do
        args="$args $1 $1 off"
        shift
    done
    kdialog --title "$title" --separate-output --checklist "$text" $args
}

xmessage_showmenu() {
    title="$1"
    shift
    text="$1"
    shift
    col1name="$1"
    shift
    col2name="$1"
    shift
    if test $# -gt 0
    then
        args="$1"
        shift
    fi
    while test $# -gt 0
    do
        args="$args,$1"
        shift
    done
    (echo "$title"; echo ""; echo "$text") | \
    xmessage -print -file - -buttons "Cancel,$args" | sed 's/Cancel//'
}

showmenu()
{
    # FIXME: call verblist_get_descriptions instead of scraping usage() ?
    case $MENU in
    zenity)
        echo "zenity --title 'Select a package to install' --text 'Install?' --list --checklist --column '' --column Package --column Description --height 440 --width 600 \\" > "$WISOTOOL_TMP"/zenity.sh
        usage | grep '^ [3a-z]' | sed 's/^ \([^ ]*\) *\(.*\)/FALSE "\1" '"'\2'/" | sed 's/$/ \\/' >> $WISOTOOL_TMP/zenity.sh
        todo="`sh "$WISOTOOL_TMP"/zenity.sh | tr '|' ' '`"
        ;;
    kdialog)
        packages=`usage | awk '/^ [3a-z]/ {print $1}'`
        todo="`kdialog_showmenu "wisotool" "Select a package to install" "Install?" "Package" $packages`"
        ;;
    xmessage)
        packages=`usage | awk '/^ [3a-z]/ {print $1}'`
        todo="`xmessage_showmenu "wisotool" "Select a package to install" "Install?" "Package" $packages`"
        ;;
    esac

    if test "$todo"x = x
    then
       exit 0
    fi
}

#-----  Helpers  ------------------------------------------------

# Execute with error checking
try() {
    # "VAR=foo try cmd" fails to put VAR in the environment
    # with some versions of bash if try is a shell function?!
    # Adding this explicit export works around it.
    export WINEDLLOVERRIDES
    echo Executing "$@"
    # Mark executable - needed if running on windows vista
    case "$1" in
    *.exe) chmod +x "$1" || true
      cmd /c "$@"
      ;;
    *)
      "$@"
      ;;
    esac
    status=$?
    if test $status -ne 0
    then
        die "Note: command '$@' returned status $status.  Aborting."
    fi
}

try_regedit() {
    # on windows, doesn't work without cmd /c
    case "$OS" in
    "Windows_NT") cmdc="cmd /c";;
    *) unset cmdc
    esac

    try early_wine $cmdc regedit "$@"
}

regedit() {
    die oops, bug, please report
}

try_cabextract() {
    # Not always installed, but shouldn't be fatal unless it's being used
    CABEXTRACT="`which cabextract 2>/dev/null`"
    if test ! -x "$CABEXTRACT"
    then
        die "Cannot find cabextract.  Please install it (e.g. 'sudo apt-get install cabextract' or 'sudo yum install cabextract')."
    fi

    try $CABEXTRACT "$@"
}

cabextract() {
    die oops, bug, please report
}

# At some point, make the return value controllable by a global 
# commandline option so we can see if we still need the workaround.
# Usage: workaround_wine_bug bugnumber [good-wineversion-shell-pattern]
workaround_wine_bug()
{
    if test "$WINE" = ""
    then
        echo No need to work around wine bug $1 on windows
        return 1
    fi
    echo "Checking $WINEVERSION against $2"
    if test "$2" != ""
    then
        # Using shell patterns in a variable with case is tricky, need to use eval
        checkcode="
            case $WINEVERSION in
                $2) echo No need to work around wine bug $1 in wine $WINEVERSION
                return 1
	        ;;
            esac
        "
        eval "$checkcode"
    fi
    case $1 in
    "$WISOTOOL_BLACKLIST") 
        echo wine bug $1 workaround blacklisted, skipping
        return 1
        ;;
    esac
    warn Working around wine bug $1
    return 0
}

# verify an sha1sum
verify_sha1sum() {
    wantsum=$1
    file=$2

    gotsum=`$SHA1SUM < $file | sed 's/ .*//'`
    if [ "$gotsum"x != "$wantsum"x ]
    then
       die "sha1sum mismatch!  Rename $file and try again."
    fi
}

# Escape entities for URL usage
# Usage: url_encode < to_filter > filtered
# See RFC3986.
url_encode() {
    perl -e '
        while (<>) {
            s/\n//;
            s/([^A-Za-z0-9\-\._~])/sprintf("%%%02X", ord($1))/ge;
            print;
        }
    '
    return $?
}

# Download a file
# Usage: package url [sha1sum [filename [cookie jar]]]
# Caches downloads in wisotoolcache/$package
download() {
    if [ "$4"x != ""x ]
    then
        file="$4"
    else
        file=`basename "$2"`
    fi
    cache="$WISOTOOL_CACHE/$1"
    mkdir -p "$cache"
    if test ! -s "$cache/$file" && test -f "$cache/$file"
    then
        # zero size - bad download?
        rm "$cache/$file"
    fi
    if test "$nosizecheck" != "" || test ! -f "$cache/$file"
    then
        cd "$cache"
        # Mac folks tend to have curl rather than wget
        # On Mac, 'which' doesn't return good exit status
        # Need to jam in --header "Accept-Encoding: gzip,deflate" else
        # redhat.com decompresses liberation-fonts.tar.gz!
        echo Downloading $2
        if [ -x "`which wget 2>/dev/null`" ]
        then
           # Use -nd to insulate ourselves from people who set -x in WGETRC
           # [*] --retry-connrefused works around the broken sf.net mirroring
           # system when downloading corefonts
           # [*] --read-timeout is useful on the adobe server that doesn't
           # close the connection unless you tell it to (control-C or closing
           # the socket)
           # Disable retries for gog.com (which requires higher level retries)
           wget -O "$file" -nd -c --read-timeout=300 --tries=1 --retry-connrefused --header "Accept-Encoding: gzip,deflate" ${5:+--load-cookies "$5"} "$2"
        else
           # curl doesn't get filename from the location given by the server!
           # fortunately, we know it
           curl -L -o "$file" -C - --header "Accept-Encoding: gzip,deflate" ${5:+--cookie "$5"} "$2"
        fi
        if test $? != 0
        then
            test -f "$file" && rm "$file"
            die "Downloading $2 failed"
        fi
        # Need to decompress .exe's that are compressed, else cygwin fails
        # Only affects cygwin, so don't barf if 'file' not installed
        FILE=`which file 2>/dev/null`
        case $FILE-$file in
        /*-*.exe)
            case `file $file` in
            *gzip*) mv $file $file.gz; gunzip < $file.gz > $file;;
            esac
        esac

        # On cygwin, .exe's must be marked +x
        case $file in
        *.exe) chmod +x $file ;;
        esac

        cd "$olddir"
    fi
    if [ "$3"x != ""x ]
    then
        verify_sha1sum $3  "$cache/$file"
    fi
}

set_winver() {
    echo "Setting Windows version to $1"
    cat > "$WISOTOOL_TMP"/set-winver.reg <<_EOF_
REGEDIT4

[HKEY_CURRENT_USER\Software\Wine]
"Version"="$1"

_EOF_
    try_regedit "$WISOTOOL_TMP_WIN"\\set-winver.reg
}

set_app_winver() {
    app="$1"
    version="$2"
    echo "Setting $app to $version mode"
    (
    echo REGEDIT4
    echo ""
    echo "[HKEY_CURRENT_USER\\Software\\Wine\\AppDefaults\\$app]"
    echo "\"Version\"=\"$version\""
    ) > "$WISOTOOL_TMP"/set-winver.reg

    try_regedit "$WISOTOOL_TMP_WIN"\\set-winver.reg
    rm "$WISOTOOL_TMP"/set-winver.reg
}


load_vcdmount()
{
    if test "$WINE" != ""
    then
        return
    fi

    # Call only on real Windows.
    # Sets VCD_DIR and ISO_MOUNT_ROOT

    # The only free mount tool I know for Windows Vista is Virtual CloneDrive,
    # which can be downloaded at
    # http://www.slysoft.com/en/virtual-clonedrive.html
    # FIXME: actually install it here

    # Locate vcdmount.exe.
    VCD_DIR="Elaborate Bytes/VirtualCloneDrive"
    if test ! -x "$programfilesdir_unix/$VCD_DIR/vcdmount.exe" && test ! -x "$programfilesdir_x86_unix/$VCD_DIR/vcdmount.exe"
    then
        warn "Installing Virtual CloneDrive"
        download . http://static.slysoft.com/SetupVirtualCloneDrive.exe
        # have to use cmd else vista won't let cygwin run .exe's?
        chmod +x "$WISOTOOL_CACHE"/SetupVirtualCloneDrive.exe
        cd "$WISOTOOL_CACHE"
        cmd /c SetupVirtualCloneDrive.exe
        cd "$olddir"
    fi
    if test -x "$programfilesdir_unix/$VCD_DIR/vcdmount.exe"
    then
        VCD_DIR="$programfilesdir_unix/$VCD_DIR"
    elif test -x "$programfilesdir_x86_unix/$VCD_DIR/vcdmount.exe"
    then
        VCD_DIR="$programfilesdir_x86_unix/$VCD_DIR"
    else
        die "can't find Virtual CloneDrive?"
    fi
    # FIXME: Use WMI to locate the drive named
    # "ELBY CLONEDRIVE..." using WMI as described in
    # http://delphihaven.wordpress.com/2009/07/05/using-wmi-to-get-a-drive-friendly-name/
}

iso_mount()
{
    my_img="$1"
    iso_umount

    # FIXME: Should we check somehow that the user put in the right disk?
    if [ ! -f "$my_img" ]
    then
        warn "You don't seem to have an iso in $WISOTOOL_CACHE/$PACKAGE. Please insert the disk so I can prepare one for you."
        load_iso dd
    fi
        
    if test "$WINE" = ""
    then
        load_vcdmount
        my_img_win="`$XXXPATH -w $my_img | tr '\012' ' ' | sed 's/ $//'`"
        cd "$VCD_DIR"
        try vcdmount.exe /l=$letter "$my_img_win"
        cd "$olddir"

        tries=0
        while test $tries -lt 20
        do
            for ISO_MOUNT_LETTER in e f g h i j k
            do
                ISO_MOUNT_ROOT=/cygdrive/$ISO_MOUNT_LETTER
                if find $ISO_MOUNT_ROOT -iname 'setup*' -o -iname '*.exe' -o -iname '*.msi' 
                then
                    break 2
                fi
            done
            tries=`expr $tries + 1`
            echo "Waiting for mount to finish mounting"
            sleep 1
        done
    else
        # Linux
        # FIXME: use fuseiso when posible to avoid needing sudo
        case "$SUDO" in
        gksudo)
          try $SUDO "mkdir -p $ISO_MOUNT_ROOT"
          try $SUDO "mount -o ro,loop,uid=$USERID,unhide $my_img $ISO_MOUNT_ROOT"
          ;;
        *)
          try $SUDO mkdir -p $ISO_MOUNT_ROOT
          try $SUDO mount -o ro,loop,uid=$USERID,unhide "$my_img" $ISO_MOUNT_ROOT
          ;;
        esac
        echo "Mounting as drive ${ISO_MOUNT_LETTER}:"
        # Gotta provide a symlink to the raw disc, else installers that check volume names will fail
        # FIXME: one of these gives a warning frequently, possibly on second run
        ln -sf "$my_img" "$WINEPREFIX/dosdevices/${ISO_MOUNT_LETTER}::"
        ln -sf "$ISO_MOUNT_ROOT" "$WINEPREFIX/dosdevices/${ISO_MOUNT_LETTER}:"
    fi
}

iso_umount()
{
    if test "$WINE" = ""
    then
        # Windows
        load_vcdmount
        cd "$VCD_DIR"
        try vcdmount.exe /u
        cd "$olddir"
    else
        echo "Running $SUDO umount $ISO_MOUNT_ROOT"
        case "$SUDO" in
        gksudo)
          # -l lazy unmount in case executable still running
          $SUDO "umount -l $ISO_MOUNT_ROOT"
          try $SUDO "rm -rf $ISO_MOUNT_ROOT"
          ;;
        *)
          $SUDO umount -l $ISO_MOUNT_ROOT
          try $SUDO rm -rf $ISO_MOUNT_ROOT
          ;;
        esac
        rm -f "$WINEPREFIX"/dosdevices/${ISO_MOUNT_LETTER}:
        rm -f "$WINEPREFIX"/dosdevices/${ISO_MOUNT_LETTER}::
    fi
}

mds_mount()
{

    my_img="$1"
    mds_umount

    # FIXME: will vcdmount work for mds/mdf files on windows, or do we need to use Alcohol here as well?
    if test "$WINE" = ""
    then
        load_vcdmount
        my_img_win="`$XXXPATH -w $my_img | tr '\012' ' ' | sed 's/ $//'`"
        cd "$VCD_DIR"
        try vcdmount.exe /l=$letter "$my_img_win"
        cd "$olddir"
        while ! test -d "$ISO_MOUNT_ROOT"
        do
            echo "Waiting for mount to finish"
            sleep 1
        done
    else
        # Wine

        cdemu load 0 $my_img

        sleep 60

        # FIXME: This is messy, but AFAICT, there's no way in advance to know where the drive will be mounted,
        # since it depends on the cd/dvd title from the origial media, which is embedded in the mdf/mds file.
        # Unfortunately, cdemu doesn't give an easy way to determine it, so find it with a combination of
        # cdemu, mount, and grep
        device_name=`cdemu device-mapping | grep ^0 | awk '{print $2}'`
        ISO_MOUNT_ROOT=`mount -l | grep $device_name | awk '{print $3}'`

        echo "Mounting as drive ${ISO_MOUNT_LETTER}:"
        # Gotta provide a symlink to the raw disc, else installers that check volume names will fail
        # FIXME: one of these gives a warning frequently, possibly on second run
        ln -sf "$device_name" "$WINEPREFIX/dosdevices/${ISO_MOUNT_LETTER}::"
        ln -sf "$ISO_MOUNT_ROOT" "$WINEPREFIX/dosdevices/${ISO_MOUNT_LETTER}:"
    fi
}

mds_umount()
{
    if test "$WINE" = ""
    then
        # Windows
        load_vcdmount
        cd "$VCD_DIR"
        try vcdmount.exe /u
        cd "$olddir"
    else
        if [ ! -x "`which cdemu 2>/dev/null`" ]
        then
            die "cdemu is not installed, can't mount .mds files!"
        fi
        
        # Initialize cdemu, if not already:

        # FIXME: Not sure this is 100% accurate...
        # FIXME: Should kill the cdemud session when done...
        pgrep cdemud
        cdemud_run=$?
        case $cdemud_run in
        0) echo "cdemud is already running" ;;
        1) echo "cdemud is not running, let's start one" ;
           ( cdemud -b session & ) ;
           sleep 60
           # FIXME: grep for "cdemu0: Daemon: error while performing ioctl" and die if it shows up ;
        ;;
        *) die "unknown error in cdemud_run" ;;
        esac

        # FIXME: just running 'cdemu unload 0' doesn't seem to unload, but running 'eject /media/foo' does?
        cdemu unload 0
        # Check that nothing is loaded there:
        img_name=`cdemu status | grep ^0 | awk '{print $3}'`
        if [ "$img_name" != "N/A" ]
        then
            echo "$img_name is mounted in cdemu, forcing an eject"
            device_name=`cdemu device-mapping | grep ^0 | awk '{print $2}'`
            ISO_MOUNT_ROOT=`mount -l | grep $device_name | awk '{print $3}'`
            # FIXME: Does this need sudo?
            eject $ISO_MOUNT_ROOT
            sleep 60 # Give devices time to settle
        fi

        rm -f "$WINEPREFIX"/dosdevices/${ISO_MOUNT_LETTER}:
        rm -f "$WINEPREFIX"/dosdevices/${ISO_MOUNT_LETTER}::
    fi
}

#----------------------------------------------------------------

# Executed if user kills script
cleanup()
{
  echo "Caught signal, cleaning up."
  case "$pid" in
  "") ;;
  *) kill $pid ;;
  esac
  # TODO: merge this with cleanup code at end of script
  test "$WISOTOOL_CACHE_SYMLINK" && rm -f "$WISOTOOL_CACHE_SYMLINK"
  echo "Done cleanup, quitting."
  exit 1
}

# FIXME: add support for ripping mdf/mds with Alcohol 120%
load_iso() {
   method=$1
   key="$2"

   die_if_user_not_dirowner "$WISOTOOL_CACHE"

   # Detect raw device
   dev=/dev/null
   for dev in /dev/cdrom /dev/sr0
   do
       test -b $dev && break
   done
   test $dev = /dev/null && die "can't find cd/dvd drive"

   # Hack for Gentoo - make sure we can read from the drive
   test -r $dev || sudo chmod 666 $dev

   # Wait for user to insert disc
   while ! dd if=$dev of=/dev/null count=1
   do
     sleep 1
   done

   # Copy disc to .iso file, display progress every 5 seconds
   # Use conv=noerror,sync to replace unreadable blocks with zeroes
   case $method in
   dd) 
     dd if=$dev of="$WISOTOOL_CACHE"/temp.iso bs=2048 conv=noerror,sync &
     pid=$!
     ;;
   ddrescue) 
     if test "`which ddrescue`" = ""
     then
         die "Please install ddrescue first."
     fi
     ddrescue -v -b 2048 $dev "$WISOTOOL_CACHE"/temp.iso &
     pid=$!
     ;;
   esac

   # Since we're running dd in the background, register a handler to kill it if user presses ^C
   trap cleanup 1 2 3 6
   while ps -p $pid > /dev/null 2>&1
   do
     sleep 5
     ls -l "$WISOTOOL_CACHE"/temp.iso
   done
   pid=""

   echo "Computing sha1sum..."
   # FIXME: can't handle spaces in "$WISOTOOL_CACHE"
   sum=`sha1sum "$WISOTOOL_CACHE"/temp.iso | awk '{print $1}'`
   echo "Sha1sum of iso is $sum"
   
   mv "$WISOTOOL_CACHE"/temp.iso "$WISOTOOL_CACHE"/$sum.iso
   if test "$key" != ""
   then
       # FIXME: in gui, prompt user for key if load= was chosen?
       echo "$key" > "$WISOTOOL_CACHE"/$sum.txt
   fi

   # Note: if you haven't written the verb for this disc yet,
   # the .iso won't be moved to the right directory.  
   # So when writing a new verb, first run 'sh wisotool load',
   # then write just the verblist_add part (including sha1sum), then
   # run 'sh wisotool migrate' to move the iso into the right directory,
   # and then write the rest of the verb.
   migrate_files

   eject $dev || true    # punt if eject not found (as on cygwin)
}

#----------------------------------------------------------------

ahk_do() {
   echo "$@" | sed "s/\$//" > "$WISOTOOL_TMP"/tmp.ahk
   $WINE "$programfilesdir_unix/AutoHotkey/AutoHotkey.exe" "$WISOTOOL_TMP_WIN"\\tmp.ahk
}

#----------------------------------------------------------------

load_autohotkey()
{
    test -f "$programfilesdir_unix/AutoHotkey/AutoHotkey.exe" || try sh "$WINETRICKS" -q autohotkey
}

#----------------------------------------------------------------

load_gecko()
{
    if ! test -f "$windir/system32/gecko/1.0.0/wine_gecko/nspr4.dll"
    then
        try sh "$WINETRICKS" gecko
    fi
}

#----------------------------------------------------------------

verblist_init()
{
    # Must call this before first call to verblist_add
    file_map="case \"\$1\" in "
    # Clear menu
    rm -f "$WISOTOOL_TMP"/menutext
}

verblist_finish()
{
    : # Now a no-op
}

# Add a verb's description to the menu
menu_add() {
    verbname=$1
    description="$2"
    printf " %-24s %s\n" $verbname "$description" >> "$WISOTOOL_TMP"/menutext
}

# Add a new verb
verblist_add()
{
    # Usage: verblist_add verbname "description" file1 file2 ...
    verbname=$1
    description="$2"
    case "$description" in
    *\'*) die "bug in call to verblist_add($verbname $description): you can't use apostrophes in game descriptions, it breaks the zenity menu.  Please remove." ;;
    esac
    shift
    shift
    present=''
    test $verbname != 'help' && present=' [loaded]'
    for file
    do
       file_map="$file_map \"$file\") echo $verbname;; "
       if ! test -f "$WISOTOOL_CACHE/$verbname/$file"
       then
           present=''
       fi
    done
    menu_add $verbname "$description$present"
}

# Returns true if given verb is in the list
verblist_is_legal_verb()
{
  verb=$1
  awk '{print $1}' < "$WISOTOOL_TMP"/menutext > "$WISOTOOL_TMP"/verbs
  if grep "^$verb$" "$WISOTOOL_TMP"/verbs > /dev/null
  then
      return 0
  else
      return 1
  fi
}

# Given a file, output the verb it belongs to
map_file_to_verb()
{
   eval "$file_map esac"
}

# Output a list of the verbs for which the needed files are in the cache
list_available_verbs()
{
    # Find files in cache, output pathnames without top level directory.
    # Use "while read" rather than "for", since we have some filenames with spaces.
    (cd "$WISOTOOL_CACHE"; find . -type f) | sed 's,^./[^/]*/,,' | while read file
    do
        map_file_to_verb "$file"
    done | sort -u
}

# Move any/all *.iso or *.exe still at top level into the proper subdirectory
migrate_files()
{
    for file in "$WISOTOOL_CACHE"/*.iso "$WISOTOOL_CACHE"/*.exe
    do
        barefile=`basename $file`
        verb=`map_file_to_verb $barefile`
        if test "$verb" != ""
        then
            mkdir -p "$WISOTOOL_CACHE"/$verb
            movee=`echo $file | sed 's,\(\.iso\)$\|\(\.exe\)$,.*,g'`
            echo Moving $movee to $WISOTOOL_CACHE/$verb/
            mv $movee "$WISOTOOL_CACHE"/$verb/
        fi
    done
}

#----- Verbs ----------------------------------------------------

verblist_init

#----------------------------------------------------------------

verblist_add 3dmark2000 "3DMark2000 (MadOnion.com, 2000) [download]" 3dmark2000_v11_100308.exe

load_3dmark2000() {
    load_autohotkey

    # http://www.futuremark.com/download/3dmark2000/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/3dmark2000_v11_100308.exe"
    then
        download $PACKAGE http://www.ocinside.de/download/3dmark2000_v11_100308.exe b0400d59cfd45d8c8893d3d4edc58b6285ee1502
    fi

    cd "$WISOTOOL_TMP"
    mkdir $PACKAGE
    cd $PACKAGE
    try unzip "$WISOTOOL_CACHE/$PACKAGE"/3dmark2000_v11_100308.exe
    ahk_do "
        SetTitleMatchMode, 2
        run Setup.exe
        WinWait Welcome
        ControlClick Button1  ; Next
        WinWait License
        ControlClick Button2  ; Yes
        ;WinWaitClose ahk_class #32770 ; License
        WinWait ahk_class #32770, Destination
        ControlClick Button1  ; Next
        ;WinWaitClose ahk_class #32770 ; Destination
        WinWait, Start
        ControlClick Button1  ; Next
        WinWait Registration
        ControlClick Button1  ; Next
        WinWait Complete
        ControlClick Button1  ; Unclick View Readme
        ControlClick Button4  ; Finish
    "

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\MadOnion.com\3DMark2000"
REM possible wine cmd bug: "3dmark2000" aborts, but ".\3dmark2000" works
.\3DMark2000
__EOF__

}

#----------------------------------------------------------------

verblist_add 3dmark2001 "3DMark2001 (MadOnion.com, 2001) [download]" 3dmark2001se_330_100308.exe

load_3dmark2001() {
    load_autohotkey

    # http://www.futuremark.com/download/3dmark2001/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE"/3dmark2001se_330_100308.exe
    then
        download $PACKAGE http://www.ocinside.de/download/3dmark2001se_330_100308.exe 643bacbcc1615bb4f46d3b045b1b8d78371a6b54
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run 3dmark2001se_330_100308.exe
        WinWait ahk_class #32770 ; welcome
        ControlClick Button2  ; Next
        sleep 5000
        WinWait ahk_class #32770 ; License
        ControlClick Button2  ; Next
        WinWait ahk_class #32770, Destination
        ControlClick Button1  ; Next
        WinWait ahk_class #32770, Start
        ControlClick Button1  ; Next
        WinWait,, Registration
        ControlClick Button2  ; Next
        WinWait,, Complete
        ControlClick Button1  ; Unclick View Readme
        ControlClick Button4  ; Finish
    "
}

#----------------------------------------------------------------

verblist_add 3dmark03 "3D Mark 03 (Futuremark, 2003) [download]" 3DMark03_v360_1901.exe

load_3dmark03() {
    load_autohotkey

    # http://www.futuremark.com/benchmarks/3dmark03/download/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/3DMark03_v360_1901.exe"
    then
        download $PACKAGE http://www.bulletproofnerds.com/uploadedfiles/futuremark/3DMark03_v360_1901.exe 46a439101ddbbe3c9563b5e9651cb61b46ce0619
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    warn "Don't use mouse while this installer is running.  Sorry..."
    # This old installer doesn't seem to be scriptable the usual way, so spray and pray.
    ahk_do "
        run 3DMark03_v360_1901.exe
        Sleep 4000
        ; Welcome
        Send {Enter}
        Sleep 2000
        ; Accept license
        Send a
        Send {Enter}
        Sleep 2000
        ; Choose Destination
        Send {Enter}
        Sleep 2000
        ; Begin install
        Send {Enter}
        ; Wait for install to finish
        Sleep 35000
        ; Purchase later
        Send {Tab}
        Send {Tab}
        Send {Enter}
        ; Uncheck readme
        Send {Space}
        Send {Tab}
        Send {Tab}
        Send {Enter}
    "
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Futuremark\3DMark03"
3DMark03
__EOF__
}

#----------------------------------------------------------------

verblist_add 3dmark05 "3D Mark 05 (Futuremark, 2005) [download]" 3DMark05_v130_1901.exe

load_3dmark05() {
    load_autohotkey

    # http://www.futuremark.com/download/3dmark05/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/3DMark05_v130_1901.exe"
    then
        download $PACKAGE http://www.bulletproofnerds.com/uploadedfiles/futuremark/3DMark05_v130_1901.exe 8ad6bc2917e22edf5fc95d1fa96cc82515093fb2
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        run 3DMark05_v130_1901.exe
        WinWait ahk_class #32770, Welcome
        Send {Enter}
        WinWait, ahk_class #32770, License
        ControlClick Button1 ; Accept
        ControlClick Button4 ; Next
        WinWait, ahk_class #32770, Destination
        ControlClick Button1 ; Next
        WinWait, ahk_class #32770, Install
        ControlClick Button1 ; Install
        WinWait, ahk_class #32770, Purchase
        ControlClick Button4 ; Later
        WinWait, ahk_class #32770, Complete
        ControlClick Button1 ; Uncheck view readme
        ControlClick Button3 ; Finish
    "
    ARGS=""
    if workaround_wine_bug 22392
    then
        warn "You must run the app with the -nosysteminfo option to avoid a crash on startup"
        ARGS="-nosysteminfo"
    fi
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Futuremark\3DMark05"
3DMark05 $ARGS
__EOF__
}

#----------------------------------------------------------------

verblist_add 3dmark06 "3D Mark 06 (Futuremark, 2006) [download]" 3DMark06_v120_1901.exe

load_3dmark06() {
    load_autohotkey

    # http://www.futuremark.com/benchmarks/3dmark06/download/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/3DMark06_v120_1901.exe"
    then
        download $PACKAGE http://www.bulletproofnerds.com/uploadedfiles/futuremark/3DMark06_v120_1901.exe 2e4a52d5b0f7caebd7b4407dfa9e258ac623b5dd
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        run 3DMark06_v120_1901.exe
        WinWait ahk_class #32770, Welcome
        Send {Enter}
        WinWait, ahk_class #32770, License
        ControlClick Button1 ; Accept
        ControlClick Button4 ; Next
        WinWait, ahk_class #32770, Destination
        ControlClick Button1 ; Next
        WinWait, ahk_class #32770, Install
        ControlClick Button1 ; Install
        WinWait ahk_class OpenAL Installer
        ControlClick Button2 ; OK
        WinWait ahk_class #32770
        ControlClick Button1 ; OK
        WinWait, ahk_class #32770, Purchase
        ControlClick Button4 ; Later
        WinWait, ahk_class #32770, Complete
        ControlClick Button1 ; Uncheck view readme
        ControlClick Button3 ; Finish
        WinWaitClose, ahk_class #32770, Complete
    "

    if workaround_wine_bug 9210
    then
        warn "You may need to apply the patch in http://bugs.winehq.org/show_bug.cgi?id=9210 to fix pCaps->MaxPointSize, or the benchmark will warn that shader model 2.0 is not present, and refuse to run."
    fi

    if workaround_wine_bug 22393
    then
        # "Demo" button doesn't work without this
        sh "$WINETRICKS" -q d3dx9_28 d3dx9_36
    fi

    ARGS=""
    if workaround_wine_bug 22392
    then
        warn "You must run the app with the -nosysteminfo option to avoid a crash on startup"
        ARGS="-nosysteminfo"
    fi

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Futuremark\3DMark06"
3DMark06 $ARGS
__EOF__
}

#----------------------------------------------------------------

verblist_add algodoo_demo  "Algodoo Demo (Algoryx, 2009) [download]" Algodoo_1_7_1-Win32.exe

load_algodoo_demo() {
    load_autohotkey
    download $PACKAGE  http://www.algodoo.com/download/Algodoo_1_7_1-Win32.exe

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        run, Algodoo_1_7_1-Win32.exe
        SetTitleMatchMode, 2
        winwait, Algodoo
	send {Enter}
        winwait, Algodoo, License
	send {Tab}a{Space}{Enter}
        winwait, Algodoo, Destination
	send {Enter}
        winwait, Algodoo, shortcuts
	send {Enter}
        winwait, Algodoo, Select Additional Tasks
	send {Enter}
        winwait, Algodoo, Ready to Install
	send {Enter}
        winwait, Algodoo, Completing
	send {Space}{Tab}{Space}{Tab}{Space}{Enter}   ; decline to run app or view tutorials
    "
    cd "$olddir"

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Algodoo"
algodoo
__EOF__
}

#----------------------------------------------------------------

verblist_add aa3  "Americas Army 3 (U.S. Army, Ubisoft, 2009) [download]" aa3.tar

load_aa3() {
    # This verb is special. It's forked from load_steam_app(), for two reasons:
    # A) the installer has an extra window to accept the EULA
    # B) the game doesn't actually need Steam to run. Once it's installed with Steam,
    #    you can move the $steam_dir/steamapps/common/america's army 3 folder to C:\aa3
    #    and it'll run fine (after installing the necessary winetricks workarounds).
    # So, we'll install with Steam if the files aren't cached, then tar them up. Future
    # 'installs', will unpack the tar to C:\aa3 (and winetricks/create .bat file).
    
    if [ ! -f "$WISOTOOL_CACHE/$PACKAGE/$PACKAGE.tar" ]
    then
        if [ ! "$STEAM_USER" -a ! -f "$WISOTOOL_CACHE"/STEAM_USER ]
        then
            die "You need to set STEAM_USER variable in your environment or put it in "$WISOTOOL_CACHE"/STEAM_USER"
        elif [ ! "$STEAM_USER" -a -f "$WISOTOOL_CACHE"/STEAM_USER ]
        then
            STEAM_USER=`cat "$WISOTOOL_CACHE"/STEAM_USER`
        fi

        if [ ! "$STEAM_PASS" -a ! -f "$WISOTOOL_CACHE"/STEAM_PASS ]
        then
            die "You need to set STEAM_PASS variable in your environment or put it in "$WISOTOOL_CACHE"/STEAM_PASS"
        elif [ ! "$STEAM_PASS" -a -f "$WISOTOOL_CACHE"/STEAM_PASS ]
        then
            STEAM_PASS=`cat "$WISOTOOL_CACHE"/STEAM_PASS`
        fi

        steam_dir="$programfilesdir_unix/Steam"

        load_autohotkey
        test -f "$steam_dir/Steam.exe" || try sh $WINETRICKS -q steam

        app_id="13140"
        game_title="America's Army 3"
        game_cache_file="aa3_public_client.ncf"
        game_folder="america's army 3"
        
        cd "$steam_dir"
        sleep 5
        ahk_do "
        run, Steam.exe -login $STEAM_USER $STEAM_PASS
        Winwait, Steam - Updating,,60
        Loop
        {
            SetTitleMatchMode, Slow
            IfWinExist, Steam - Updating
                sleep 10000
            IfWinNotExist, Steam - Updating
                break
        }
        sleep 30000
        run, steam://install/$app_id
        
        ; Info screen, disk space required, etc.
        winwait, Install - $game_title
        winactivate, Install - $game_title
        ; FIXME: How long should this take?
        sleep 10000
        send {enter}
        sleep 10000

        ; Install shortcuts?
        winwait, Install - $game_title
        winactivate, Install - $game_title
        ; FIXME: How long should this take?
        sleep 10000
        send {enter}
        sleep 10000
        
        ; Accept EULA?
        winwait, Install - $game_title
        winactivate, Install - $game_title
        ; FIXME: How long should this take?
        sleep 10000
        send {enter}
        sleep 10000

        ; Here, it's getting the .gcf/.ncf files. This is normally quick, but can take a long time.
        ; Most finish in a few seconds, but the Total War demos takes a couple minutes.
        ; So, we'll exit AHK, then wait for all the game files to be present,
        ; before continuing the install.
        exit
        "

        # FIXME: Is this a long enough sleep?
        sleep 30
        
        ahk_do "
        winwait, Install - $game_title
        winactivate, Install - $game_title
        ; FIXME: How long should this take?
        sleep 10000
        send {enter}
        "

        dl_log="$steam_dir/logs/download_log.txt"
        while true
        do
            grep "SetHasAllLocalContent(true) called for $app_id" "$dl_log" && break
            sleep 15
        done

        sleep 30
        $WINE Steam.exe -shutdown
        mkdir -p "$WISOTOOL_CACHE/$PACKAGE"
        cd "steamapps/common/$game_folder"
        tar -cf "$WISOTOOL_CACHE/$PACKAGE/$PACKAGE.tar" .
        cd ..
        mv "$game_folder" "$DRIVE_C/aa3"
    else
        mkdir -p "$DRIVE_C/$PACKAGE"
        cd "$DRIVE_C/$PACKAGE"
        tar -xf "$WISOTOOL_CACHE/$PACKAGE/$PACKAGE.tar"
    fi
    
if workaround_wine_bug 17630
then
    sh "$WINETRICKS" -q d3dx10
fi

if workaround_wine_bug 22501
then
    sh "$WINETRICKS" -q vcrun2005
fi

if workaround_wine_bug 23660
then
    sh "$WINETRICKS" -q d3dx9
fi

cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "c:\\aa3\\Binaries"
AA3Game.exe
__EOF__

}

#----------------------------------------------------------------

verblist_add msaoe_demo  "Age of Empires Demo (Microsoft, 1997) [download]" MSAoE.exe

load_msaoe_demo() {
    load_autohotkey
    download $PACKAGE  http://download.microsoft.com/download/aoe/Trial/1.0/WIN98/EN-US/MSAoE.exe 23630a65ce4133038107f3175f8fc54a914bc2f3

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        run, MSAoE.exe
        SetTitleMatchMode, 2
        winwait, Microsoft Age of Empires Trial Version
        ControlClick, Button1
        winwait, End User License Agreement
        ControlClick, Button1
        winwait, Microsoft Age of Empires Trial Version, Setup will install
        ControlClick Button2
        winwait, Microsoft Age of Empires Trial Version, Setup has successfully
        ControlClick Button1
    "
    cd "$olddir"

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Microsoft Games\Age of Empires Trial"
empires
__EOF__
}

#----------------------------------------------------------------

verblist_add apb "APB: All Points Bulletin (Electronic Arts, 2010)" APB_North_America_Installer.exe

load_apb() {
    load_autohotkey

    download $PACKAGE http://rtworlds.http.internapcdn.net/rtworlds/NA/APB/BETA/INSTALLER/1.1.0.538715/APB_North_America_Installer.exe c40071616096becb72f10a2e7721ef340c48ad4e

    sh "$WINETRICKS" -q dotnet20

    cd "$WISOTOOL_CACHE/$PACKAGE"

    if workaround_wine_bug 23527
    then
        sh "$WINETRICKS" -q gdiplus
    fi

    ahk_do "
    SetTitleMatchMode, 2
    run, APB_North_America_Installer.exe
    winwait, Installer language, Please select the language you would like the installer to run in
    sleep 1000
    controlclick, Button1, Installer language, Please select the language you would like the installer to run in
    winwait, APB North America v1.1.0.538715, Welcome to the APB All Points Bulletin Setup Wizard
    sleep 1000
    controlclick, Button2, APB North America v1.1.0.538715, Welcome to the APB All Points Bulletin Setup Wizard
    winwait, APB North America v1.1.0.538715, Please review the license terms before installing APB All Points Bulletin.
    sleep 1000
    controlclick, Button4, APB North America v1.1.0.538715, Please review the license terms before installing APB All Points Bulletin.
    sleep 1000
    controlclick, Button2, APB North America v1.1.0.538715, Please review the license terms before installing APB All Points Bulletin.
    winwait, APB North America v1.1.0.538715, Third Party Library List
    sleep 1000
    controlclick, Button5, APB North America v1.1.0.538715, Third Party Library List
    sleep 1000
    controlclick, Button2, APB North America v1.1.0.538715, Third Party Library List
    winwait, APB North America v1.1.0.538715, System Check
    sleep 1000
    controlclick, Button2, APB North America v1.1.0.538715, System Check
    winwait, APB North America v1.1.0.538715, Results of the system scan.
    sleep 1000
    controlclick, Button2, APB North America v1.1.0.538715, Results of the system scan.
    winwait, APB North America v1.1.0.538715, Choose the folder in which to install APB All Points Bulletin.
    sleep 1000
    controlclick, Button2, APB North America v1.1.0.538715, Choose the folder in which to install APB All Points Bulletin.
    winwait, APB North America v1.1.0.538715, APB All Points Bulletin will be installed in C:\Program Files\Realtime Worlds\APB North America. Is this okay?
    sleep 1000
    controlclick, Button1, APB North America v1.1.0.538715, APB All Points Bulletin will be installed in C:\Program Files\Realtime Worlds\APB North America. Is this okay?
    winwait, APB North America v1.1.0.538715, Choose a Start Menu folder for the APB All Points Bulletin shortcuts.
    sleep 1000
    controlclick, Button2, APB North America v1.1.0.538715, Choose a Start Menu folder for the APB All Points Bulletin shortcuts.
    winwait, APB North America v1.1.0.538715, Setup was completed successfully.
    sleep 1000
    controlclick, Button2, APB North America v1.1.0.538715, Setup was completed successfully.
    winwait, APB North America v1.1.0.538715, The APB Launcher has been installed.
    sleep 1000
    controlclick, Button2, APB North America v1.1.0.538715, The APB Launcher has been installed.
    ; Runs after install. However, also crashes in current (1.2-rc6) wine. For now, kill both, just in case...
    process, close, APBLauncher.exe
    process, close, BugReport.exe
    "
}

#----------------------------------------------------------------

verblist_add assassinscreed "Assassins Creed (Ubisoft, 2008)" a62112860423b32bf3ea77df6f5fe0b60c772de2.iso

load_assassinscreed() {
    load_autohotkey

    if workaround_wine_bug 22392
    then
        # Don't hang at a dialog box when Detection crashes
        sh "$WINETRICKS" nocrashdialog
    fi

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/a62112860423b32bf3ea77df6f5fe0b60c772de2.iso
    ahk_do "
        run ${ISO_MOUNT_LETTER}:setup.exe
        SetTitleMatchMode, 2
        winwait, InstallShield Wizard, Language
        ; wine bug? - clicking on Next does nothing until you move the mouse over the installer window
        ;ControlClick Next, InstallShield Wizard
        Send {Enter}
        winwait, InstallShield Wizard, Welcome
        ControlClick Next, InstallShield Wizard
        winwait, InstallShield Wizard, License
        sleep 500
        send a{Enter}
        winwait, InstallShield Wizard, begin
        sleep 1000
        ControlClick &Install, InstallShield Wizard
        winwait, Product Registration, register
        ControlClick Never, Product Registration
        ControlClick Button1, Product Registration
        winwait, InstallShield Wizard, inish
        send {Enter}
    "
    iso_umount

    # Should run AssassinsCreed_Launcher.exe, but that fails on Wine
    # Should give option to run AssassinsCreed_Dx10.exe, but that fails on Wine
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Ubisoft\Assassin's Creed"
AssassinsCreed_Dx9.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add avatar_demo    "James Camerons Avatar The Game Demo (Ubisoft, 2009) [download]" Avatar_The_Game_Demo.exe

load_avatar_demo()
{
    load_autohotkey
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/Avatar_The_Game_Demo.exe"
    then
        mkdir -p "$WISOTOOL_CACHE/$PACKAGE"
        die "You must first download the demo from http://www.bigdownload.com/games/james-camerons-avatar-the-game/pc/james-camerons-avatar-the-game-demo/ and place the exe in $WISOTOOL_CACHE/$PACKAGE"
    fi

    if workaround_wine_bug 23094
    then
        try sh winetricks -q vcrun2005
    fi

    mkdir -p "$WISOTOOL_TMP/$PACKAGE"
    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, Avatar_The_Game_Demo.exe
        winwait, WinRAR, Install
        send $WISOTOOL_TMP_WIN\\$PACKAGE
        controlclick, Button2
        winwaitclose, WinRAR
        sleep 1000
        run, setup.exe
        winwait, Language
        controlclick, Button1
        winwait, AVATAR, Welcome
        controlclick, Button1
        winwait, AVATAR, License
        controlclick, Button5
        controlclick, Button2
        winwait, AVATAR, setup type
        controlclick, Button2
        ;Strange CRC error workaround. Will check this out. Stay tuned.
        sleep 1000
        ifwinactive, CRC Error
        {
          controlclick, Button5
        }
        winwait, AVATAR, Complete
        controlclick, Button4 
    "
    cd "$olddir"
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Ubisoft\Demo\James Cameron's AVATAR - THE GAME (Demo)\bin"
"AvatarDemo.exe"
__EOF__
}

#----------------------------------------------------------------

# http://appdb.winehq.org/objectManager.php?sClass=version&iId=408
verblist_add baldursgate2       "Baldurs Gate 2 - Shadows of Amn (Bioware, 2000)" \
  cc9359dce1a7be6c64bb6f8e6dea6d14d4a5f716.iso \
  429872605dad10433c3c581a1c11eba4d0988c46.iso \
  a6d18fcd7d16ddafbda7aa028b117566b1e09d2a.iso \
  94ed41768949c89a1a6479305f00a9cee1d2dcd5.iso

load_baldursgate2() {
    load_autohotkey

    # Possible wine bug: cd is still in use, even if wine eject is used. Workaround it by
    # copying all the cd's to a directory, and running the installer from there.
    # You still need the first CD mounted at the end, however...
    if test ! -d "$WISOTOOL_TMP"/$PACKAGE/tempcd
    then
        try mkdir -p "$WISOTOOL_TMP"/$PACKAGE/tempcd
        iso_mount "$WISOTOOL_CACHE"/$PACKAGE/cc9359dce1a7be6c64bb6f8e6dea6d14d4a5f716.iso
        sleep 5
        try cp -r "$ISO_MOUNT_ROOT"/* "$WISOTOOL_TMP"/$PACKAGE/tempcd
        iso_mount "$WISOTOOL_CACHE"/$PACKAGE/429872605dad10433c3c581a1c11eba4d0988c46.iso
        sleep 5
        try cp -r "$ISO_MOUNT_ROOT"/* "$WISOTOOL_TMP"/$PACKAGE/tempcd
        iso_mount "$WISOTOOL_CACHE"/$PACKAGE/a6d18fcd7d16ddafbda7aa028b117566b1e09d2a.iso
        sleep 5
        try cp -r "$ISO_MOUNT_ROOT"/* "$WISOTOOL_TMP"/$PACKAGE/tempcd
        iso_mount "$WISOTOOL_CACHE"/$PACKAGE/94ed41768949c89a1a6479305f00a9cee1d2dcd5.iso
        sleep 5
        try cp -r "$ISO_MOUNT_ROOT"/* "$WISOTOOL_TMP"/$PACKAGE/tempcd
    fi
    
    # Will perform a full install, so no cd's needed
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/cc9359dce1a7be6c64bb6f8e6dea6d14d4a5f716.iso
    
    ahk_do "
        SetTitleMatchMode, 2
        run "$WISOTOOL_TMP"/$PACKAGE/tempcd/setup.exe
        winwait, Baldur's Gate, Welcome to the Baldur's Gate
        sleep 1000
        ControlClick, Button1, Baldur's Gate, Welcome to the Baldur's Gate
        winwait, Baldur's Gate, Please read the following License Agreement
        sleep 1000
        ControlClick, Button2, Baldur's Gate, Please read the following License Agreement
        winwait, Baldur's Gate, Setup will install Baldur's Gate
        sleep 1000
        ControlClick, Button1, Baldur's Gate, Setup will install Baldur's Gate
        winwait, Baldur's Gate, Click the type of Setup you prefer
        sleep 1000
        ControlClick, Listbox1, Baldur's Gate, Click the type of Setup you prefer
        send {F}
        ControlClick, Button2, Baldur's Gate, Click the type of Setup you prefer
        winwait, Baldur's Gate, Setup will add program icons
        sleep 1000
        ControlClick, Button2, Baldur's Gate, Setup will add program icons
        winwait, Setup Needs The Next Disk
        sleep 1000
        Send {Home}
        Send {Shift down}
        Send {End}
        Send I:{Enter}
        winwait, Information
        sleep 1000
        ControlClick, Button1, Information
        Sleep 5000
        process, wait, Promo.exe, 5
        promopid = %ErrorLevel%
        winclose, ahk_pid %promopid%
        winwait, Baldur's Gate, Setup has finished installing
        sleep 1000
        ControlClick, Button4, Baldur's Gate, Setup has finished installing
        "
    try chmod +w -R "$WISOTOOL_TMP"/$PACKAGE/tempcd
    try rm -rf "$WISOTOOL_TMP"/$PACKAGE/tempcd

    # Install latest patch
    download baldursgate2 http://downloads.bioware.com/baldursgate2/Baldur%27sGateII-ShadowsofAmnPatchENGLISH.exe 4706c0dc1e282bae14946c87a38e2781f89ebdc4
    # AHK doesn't like its name...
    try cp -f "$WISOTOOL_CACHE/baldursgate2/Baldur%27sGateII-ShadowsofAmnPatchENGLISH.exe" "$WISOTOOL_TMP/baldurs_gate_2_patch.exe"

    cd "$WISOTOOL_TMP"
    ahk_do "
        SetTitleMatchMode, 2
        run, baldurs_gate_2_patch.exe
        winwait InstallShield Wizard, Welcome to the InstallShield Wizard
        sleep 1000
        ControlClick Button1, InstallShield Wizard, Welcome to the InstallShield Wizard
        winwait InstallShield Wizard, InstallShield Wizard Complete
        sleep 1000
        ControlClick Button4, InstallShield Wizard, InstallShield Wizard Complete
        exit"
    cd -
    try rm "$WISOTOOL_TMP/baldurs_gate_2_patch.exe"
    
    if workaround_wine_bug 22482
    then
        sh "$WINETRICKS" -q ddr=opengl
        warn "Enabling 3d acceleration in BGConfig.exe will improve performance."
    fi
    
    if workaround_wine_bug 22493
    then
        warn "Enabling 3d acceleration in BGConfig.exe will improve performance."
    fi

    if test ! "$WINE" = ""
    then
        warn "Until wine bug 22511 is fixed, you should use a virtual desktop, or baldur's gate will only take up part of your screen in full screen mode."
    fi
}

#----------------------------------------------------------------

verblist_add bfbc2       "Battlefield Bad Company 2 (EA, 2010)" \
  9ec587f1eda0f8bf13f485526e3c46e4f9d477a6.iso

load_bfbc2() {
    load_autohotkey
    exedir="$programfilesdir_x86_unix/Electronic Arts/Battlefield Bad Company 2"

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/9ec587f1eda0f8bf13f485526e3c46e4f9d477a6.iso
    BFBC2_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/9ec587f1eda0f8bf13f485526e3c46e4f9d477a6.txt | tr -d -`
    ahk_do "
        SetTitleMatchMode, 2
        run ${ISO_MOUNT_LETTER}:setup.exe
        winwait, Bad Company, English
        ControlClick, Next, Bad Company
        winwait, Bad Company, Registration Code
        send {RAW}$BFBC2_KEY
        ControlClick, Next, Bad Company, Registration Code
        winwait, Bad Company, Setup Wizard will install
        ControlClick, Button1, Bad Company, Setup Wizard
        winwait, Bad Company, License Agreement
        ControlClick, Button1, Bad Company, License Agreement
        ControlClick, Button3, Bad Company, License Agreement
        winwait, Bad Company, End-User License Agreement
        ControlClick, Button1, Bad Company, License Agreement
        ControlClick, Button3, Bad Company, License Agreement
        winwait, Bad Company, Destination Folder
        ControlClick, Button1, Bad Company, Destination Folder
        winwait, Bad Company, Ready to install
        ControlClick, Install, Bad Company, Ready to install
        winwait, Authenticate Battlefield
        ControlClick, Disc authentication, Authenticate Battlefield
        ControlClick, Button4, Authenticate Battlefield
        winwait, Bad Company, PunkBuster
        ControlClick, Button4, Bad Company, PunkBuster
        ControlClick, Finish, Bad Company
    "
    iso_umount

    warn "Patching to latest version..."
    cd "$exedir"
    ahk_do "
        SetTitleMatchMode, 2
        run, BFBC2Updater.exe
        winwait, Updater, have to update to
        ControlClick, Yes, Updater, have to update
        winwait, Updater, successfully updated
        ControlClick,No, Updater, successfully updated
    "

    if workaround_wine_bug 22762
    then
        cd "$DRIVE_C/users/$USERNAME/My Documents"
        if test -f BFBC2/settings.ini
        then
            mv BFBC2/settings.ini BFBC2/oldsettings.ini
            sed 's,DxVersion=auto,DxVersion=9,;
                 s,Fullscreen=true,Fullscreen=false,' BFBC2/oldsettings.ini > BFBC2/settings.ini 
        else
            mkdir -p BFBC2
            echo "[Graphics]" > BFBC2/settings.ini
            echo "DxVersion=9" >> BFBC2/settings.ini
        fi
    fi
    cd "$olddir"
    
    if workaround_wine_bug 22961
    then
        warn "If you get a Securom 'No CD/DVD error', check your mount settings. See http://bugs.winehq.org/show_bug.cgi?id=22961 for more info."
    fi
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Electronic Arts\\Battlefield Bad Company 2"
BFBC2Game.exe
__EOF__
}

#----------------------------------------------------------------

# http://appdb.winehq.org/objectManager.php?sClass=version&iId=9320
# Fails to install with an iso, need to use an mdf/mds from Alcohol 120% on Windows
# FIXME: mds/mdf files have different sha1sum's, and depending on the rip settings, the mds might as well?
# Sha1sum's:
# plain iso, from dd: deaf00ebee6e73aecf38f704c3f516008a68d888
# mds: 391042ea19b4eace5d532dbade10931ebbc4def6
# mdf: deaf00ebee6e73aecf38f704c3f516008a68d888
verblist_add bioshock       "Bioshock (2K Games, 2007)" \
  391042ea19b4eace5d532dbade10931ebbc4def6.mds

load_bioshock() {
    load_autohotkey
    
    # Bioshock needs MSVCP80.dll to run, which Wine doesn't have yet.
    if workaround_wine_bug 22501
    then
        sh "$WINETRICKS" -q vcrun2005
    fi
    
    # Will perform a full install, so no cd's needed
    mds_mount "$WISOTOOL_CACHE/$PACKAGE/391042ea19b4eace5d532dbade10931ebbc4def6.mds"

    # Setup cdemu for Bioshock (dpm on, tr off):
    # FIXME: I'm assuming different programs may want different emulation settings. If not, move up to mds_mount().
    cdemu dpm-emulation 0 1
    cdemu tr-emulation 0 0

    # Don't trim the hyphen's "-", the installer won't proceed without them.
    BIOSHOCK_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/391042ea19b4eace5d532dbade10931ebbc4def6.txt`
    
    ahk_do "
        SetTitleMatchMode, 2
        run ${ISO_MOUNT_LETTER}:setup.exe
        winwait, BioShock - InstallShield Wizard, Choose Setup Language
        sleep 2000
        ControlClick, Button3, BioShock - InstallShield Wizard, Choose Setup Language
        ControlClick, Button3, BioShock - InstallShield Wizard, Choose Setup Language ; Installer seems fidgety
        winwait, BioShock - InstallShield Wizard, Welcome to the InstallShield Wizard for BioShock
        sleep 1000
        ControlClick, Button1, BioShock - InstallShield Wizard, Welcome to the InstallShield Wizard for BioShock
        winwait, BioShock - InstallShield Wizard, Please read the following license agreement carefully
        sleep 1000
        ControlClick, Button5, BioShock - InstallShield Wizard, Please read the following license agreement carefully
        sleep 1000
        ControlClick, Button2, BioShock - InstallShield Wizard, Please read the following license agreement carefully
        winwait, BioShock - InstallShield Wizard, Select the setup type to install
        sleep 1000
        ControlClick, Button2, BioShock - InstallShield Wizard, Select the setup type to install
        winwait, BioShock - InstallShield Wizard, Click Install to begin the installation
        ControlClick, Button1, BioShock - InstallShield Wizard, Click Install to begin the installation
        Loop
        {
            ; Detect if Securom likes the mounted ISO or not. If so, continue the install. If not, exit since the install will fail.
            SetTitleMatchMode, Slow
            IfWinExist, BioShock - InstallShield Wizard, The InstallShield Wizard has successfully installed BioShock
                break
            IfWinExist, Bioshock, Please insert the original disc instead of a backup (1000)
            {
                exit 1
            }
            sleep 10000
        }
        sleep 1000
        ControlClick, Button6, BioShock - InstallShield Wizard, The InstallShield Wizard has successfully installed BioShock
        sleep 1000
        ControlClick, Button4, BioShock - InstallShield Wizard, The InstallShield Wizard has successfully installed BioShock
        winwait, Welcome, &Next
        Sleep 1000
        ControlClick, Button2, Welcome, &Next
        winwait, Enter your serial number, &Activate
        Sleep 1000
        ControlClick, Edit1, Enter your serial number, &Activate
        send {Raw}$BIOSHOCK_KEY
        Sleep 1000
        ControlClick, Button1, Enter your serial number, &Activate
        winwait, Activation Successful
        Sleep 1000
        Controlclick, Button3, Activation Successful
        " || (  wineserver -k ; warn "Bioshock failed to install properly, likely the Securom check failed" )

    # According to the AppDB, 1.1 may have problems with Wine. For now, don't run it.
    # FIXME: Test and if there's a Wine bug, file one/put this in an if workaround_wine_bug().
    #
    #download $PACKAGE http://downloads.2kgames.com/bioshock/patch/Bioshock_Version_11_Patch_Worldwide_Retail.zip
    #cd $WISOTOOL_TMP
    #unzip "$WISOTOOL_CACHE/$PACKAGE/Bioshock_Version_11_Patch_Worldwide_Retail.zip"
    #ahk_do "
    #    run Bioshock Version 1.1 Patch Worldwide Retail.exe
    #    winwait, BioShock 1.1 Patch, This patch is to be applied ONLY to the Uncensored Retail Version of BioShock
    #    sleep 1000
    #    ControlClick, Button1, BioShock 1.1 Patch, This patch is to be applied ONLY to the Uncensored Retail Version of BioShock
    #    winwait, Location Confirmation, Is located at
    #    sleep 1000
    #    ControlClick, Button1, Location Confirmation, Is located at
    #    winwait, License Agreement, Please read the following license agreement carefully.
    #    sleep 1000
    #    ControlClick, Button1, License Agreement, Please read the following license agreement carefully.
    #    winwait, BioShock Patched Successfully!, BioShock patched to version 1.1 successfully!
    #    sleep 1000
    #    ControlClick, Button1, BioShock Patched Successfully!, BioShock patched to version 1.1 successfully!
    #    "
    if workaround_wine_bug 6971
    then
        sh "$WINETRICKS" -q mwo=force
    fi

    mds_umount
}

#----------------------------------------------------------------

verblist_add bioshock_demo       "Bioshock Demo (2K Games, 2007)" \
  nzd_BioShockPC.zip

load_bioshock_demo() {
    load_autohotkey
    download $PACKAGE http://us.download.nvidia.com/downloads/nZone/demos/nzd_BioShockPC.zip 7a19186602cec5210e4505b58965e8c04945b3cf
    cd "$DRIVE_C"
    rm -rf bioshock-temp
    mkdir bioshock-temp
    cd bioshock-temp
    try unzip -q "$WISOTOOL_CACHE/$PACKAGE"/nzd_BioShockPC.zip
    try cd "BioShock PC Demo"
    ahk_do "
        SetTitleMatchMode, 2
        run setup.exe
        winwait, BioShock Demo - InstallShield Wizard, Choose Setup Language
        sleep 2000
        ControlClick, Button3
        ControlClick, Button3
        winwait, BioShock Demo - InstallShield Wizard, Welcome
        sleep 1000
        ControlClick, Button1
        winwait, BioShock Demo - InstallShield Wizard, Please read
        sleep 1000
        ControlClick, Button5
        sleep 1000
        ControlClick, Button2
        winwait, BioShock Demo - InstallShield Wizard, Select the setup type
        sleep 1000
        ControlClick, Button2
        winwait, BioShock Demo - InstallShield Wizard, Click Install to begin
        ControlClick, Button1
        winwait, BioShock Demo - InstallShield Wizard, The InstallShield Wizard has successfully installed BioShock
        sleep 1000
        ControlClick, Button2     ; don't launch
        ControlClick, Button6     ; don't show readme
        send {Enter}              ; finish
    "
    cd ..
    rm -rf bioshock-temp
    cd "$olddir"
}

#----------------------------------------------------------------

verblist_add blur       "Blur (Activision, 2010)" \
  30fdaf3aad82be846f26b7908c703598d5c3443d.iso

load_blur() {
    load_autohotkey
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/30fdaf3aad82be846f26b7908c703598d5c3443d.iso

    ahk_do "
        Run, ${ISO_MOUNT_LETTER}:Setup.exe
        SetTitleMatchMode, 2
        winwait, Activision, Select the language
        sleep 1000
        send {Enter}
        winwait, Blur, install Blur
        sleep 1000
        send {Enter}
        winwait, Blur, License
        sleep 1000
        ControlClick Button5
        send {Enter}
        winwait, Blur, Minimum System
        sleep 1000
        send {Enter}
        winwait, Blur, Setup Type
        sleep 1000
        send {Enter}
    "
    # Installer seems to crash at end on Win7 and Wine
    # Wait for last file to be created(Blur.exe?), then kill wineserver
    # and do the d3dx physx install by using winetricks.
    while [ ! -f "$programfilesdir_x86_unix"/Activision/Blur*/Blur.exe ]
    do
        sleep 5
    done
    # Sleep for 30 seconds to ensure that all files have been created
    # before killing the wineserver.
    sleep 30
    wineserver -k
    
    # We killed the wineserver before(or during) the d3dx9 and physx install
    # so use winetricks to install them. The game runs without the physx trick
    # but frame rate improves with physx.
    try sh "$WINETRICKS" -q d3dx9 physx
    iso_umount
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Activision\Blur*"
"Blur.exe"
__EOF__
}

#----------------------------------------------------------------

verblist_add braid_demo    "Braid Demo (Number None, 2009) [download]" braid_windows_r3.exe

load_braid_demo()
{
    load_autohotkey

    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/braid_windows_r3.exe"
    then
        download $PACKAGE "http://www.playgreenhouse.com/php/public/tracking/downloads.php?sku=NNONE-000001-01&platform=win" 7ea08ddbf5f2fb2f38057d930389b5af7d737e2c
    fi
    cd "$WISOTOOL_CACHE/$PACKAGE"
    mv downloads.php* braid_windows_r3.exe 2>/dev/null
    ahk_do "
        SetTitleMatchMode, 2
        run, braid_windows_r3.exe
        winwait, Braid, install
        controlclick, TButton1
        winwait, Braid, Destination
        controlclick, TButton3
        winwait, Braid, Ready to Install
        controlclick, TButton3
        winwait, Setup, Finishing installation
        sleep 5000
        ; Workaround_winebug 21761
        ifwinactive, Setup, ShellExecuteEx failed 
        {
            controlclick, Button1
        }
        winwait, Braid, finished
        controlclick, TButton3
    "
    cd "$olddir"

    if workaround_wine_bug 22161
    then
        try sh "$WINETRICKS" -q d3dx9_36
    fi
    
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Braid"
braid.exe
__EOF__
} 

#----------------------------------------------------------------

verblist_add braid    "Braid (Number None, 2009) [download]" braid_windows_r3.exe

load_braid()
{
    load_autohotkey

    BRAID_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/braid-key.txt`

    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/braid_windows_r3.exe"
    then
        download $PACKAGE "http://www.playgreenhouse.com/php/public/tracking/downloads.php?sku=NNONE-000001-01&platform=win" 7ea08ddbf5f2fb2f38057d930389b5af7d737e2c
    fi
    cd "$WISOTOOL_CACHE/$PACKAGE"
    mv downloads.php* braid_windows_r3.exe 2>/dev/null
    ahk_do "
        SetTitleMatchMode, 2
        run, braid_windows_r3.exe
        winwait, Braid, install
        controlclick, TButton1
        winwait, Braid, Destination
        controlclick, TButton3
        winwait, Braid, Ready to Install
        controlclick, TButton3
        winwait, Setup, Finishing installation
        sleep 5000
        ; Workaround_winebug 21761
        ifwinactive, Setup, ShellExecuteEx failed 
        {
            controlclick, Button1
        }
        winwait, Braid, finished
        controlclick, TButton3
    "

    if workaround_wine_bug 22161
    then
        try sh "$WINETRICKS" -q d3dx9_36
    fi
    
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Braid\"
"braid.exe"
__EOF__

    # Enter the key
    cd "$DRIVE_C"
    ls
    ahk_do "
        SetTitleMatchMode, 2
        run, run-$PACKAGE.bat
        winwait, Braid, Enter Registration
        controlclick, Button4
        winwait, Enter Registration
        send {RAW}$BRAID_KEY
        controlclick, Button1
    "
    sleep 5
    # FIXME: use right wineserver
    wineserver -k
    cd "$olddir"
} 

#----------------------------------------------------------------

verblist_add codmw2        "Call of Duty Modern Warfare 2 (Activision, 2009) [broken]" \
  6f572261ed954733806daf5b42edf92b3127cd14.iso \
  3c6e63504d41df4bdb2d4c57f4c5fc7b810d7df8.iso

load_codmw2()
{
    warn "This verb isn't quite ready for prime time."
    load_autohotkey
    test -f "$programfilesdir_x86_unix"/Steam/Steam.exe || try sh $WINETRICKS -q steam

    # Get user's key
    CODMW2_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/6f572261ed954733806daf5b42edf92b3127cd14.txt | tr -d -`

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/6f572261ed954733806daf5b42edf92b3127cd14.iso
    cd "$programfilesdir_x86_unix"/Steam
    ahk_do "
        SetTitleMatchMode, 2
        Run, Steam.exe -login $STEAMUSER $STEAMPW -install ${ISO_MOUNT_LETTER}:

	; Uncomment these lines if you haven't activated this game via steam on this account before.
        ;winwait, Activation
        ;MouseMove, 30, 400
        ;Click
        ;Sleep 300
        ;send {Raw}$CODMW2_KEY
        ;MouseMove, 306, 566
        ;Click
        ;winwait, Activation
        ;sleep 10000
        ;MouseMove, 310, 565
        ;Click

        winwait, Install
        sendEvent {Enter}
        ; wait for [create start menu and install] question
        sleep 5000
        sendEvent {Enter}
        winwait, Insert
    "
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/3c6e63504d41df4bdb2d4c57f4c5fc7b810d7df8.iso
    ahk_do "
        SetTitleMatchMode, 2
        Send {Enter}
	; Need to wait for install to finish.  This isn't the way to do it.  Ideally we could watch some log file.
	; The last file created seems to be
	; Program Files/Steam/steamapps/call of duty modern warfare 2 content.ncf
	; so wait for that and then another 20 seconds, say.
        winwait, ahk_class USurface_, Install
	; Now that install has finished, say [don't start app] and [finish].
        Send {Space}
        Send {Enter}
	; Now wait for the main steam interface to pop up, and close it
        winwait, ahk_class USurface_, Steam
        WinClose

	; If you choose to start the game above, you could wait for it to be ready to play here.  
        ;winwait, ahk_class USurface_8390, Ready
        ;Send {Tab}            # select Close
        ;Send {Enter}
	;winwait, Steam Login
        ;WinClose
    "
    iso_umount
    
}

#----------------------------------------------------------------

verblist_add cnc3_demo    "Command and Conquer 3 Demo (EA, 2007) [download]" CnC3Demo.exe

load_cnc3_demo()
{
    load_autohotkey

    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/CnC3Demo.exe"
    then
        download $PACKAGE http://largedownloads.ea.com/pub/demos/CommandandConquer3/CnC3Demo.exe f6af21eba2d17eb6d8bb6a131b501b41c3a7eaf7 
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, CnC3Demo.exe
        winwait, Conquer 3, free space to install
        sleep 1000
        send y
        winwait, WinZip, After installation
        sleep 1000
        send s
        winwait, Conquer 3, InstallShield
        sleep 3000
        controlclick, Button1
        winwait, Conquer 3, license
        controlclick, Button3
        controlclick, Button5
        winwait, Conquer 3, setup type
        controlclick, Button5
        winwait, Conquer 3, EA Link
        controlclick, Button1
        winwait, Conquer 3, GameSpy
        controlclick, Button1
        winwait, Conquer 3, Launch the program
        controlclick, Button1
    "
    cd "$olddir"

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Electronic Arts\\Command & Conquer 3 Tiberium Wars Demo"
CNC3Demo.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add cnc4    "Command and Conquer 4 (EA, 2010) [broken-wine-drm]" f3308e6d3a93e7b5dd2643631404e97b66a0c262.iso

load_cnc4()
{
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/f3308e6d3a93e7b5dd2643631404e97b66a0c262.iso

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, ${ISO_MOUNT_LETTER}:EASetup.exe
        winwait, Tiberian Twilight, License
        controlclick, Button1
        controlclick, Button2
        winwait, Tiberian Twilight, Standard Installation
        controlclick, Button1
        winwait, Tiberian Twilight, to exit the Setup
        controlclick, Button5
        controlclick, Button1
    "
    cd "$olddir"
    iso_umount

    # Bypass the game's launcher: see AppDB
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
"$programfilesdir_x86_win\\Electronic Arts\\Command & Conquer 4 Tiberian Twilight\\Data\\CNC4.game" -config "$programfilesdir_x86_win\\Electronic Arts\\Command & Conquer 4 Tiberian Twilight\\CNC4_English.SkuDef"
__EOF__

    # Doesn't work on Wine yet because of DRM?
}

#----------------------------------------------------------------

verblist_add darknesswithin2_demo    "Darkness Within 2 Demo (Zoetrope Interactive, 2010) [download]" DarknessWithin2Demo.exe

load_darknesswithin2_demo()
{
    load_autohotkey
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/DarknessWithin2Demo.exe"
    then
        mkdir -p "$WISOTOOL_CACHE/$PACKAGE"
        die "Please download $WISOTOOL_CACHE/$PACKAGE/DarknessWithin2Demo.exe from http://www.bigdownload.com/games/darkness-within-2-the-dark-lineage/pc/darkness-within-2-the-dark-lineage-demo"
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, DarknessWithin2Demo.exe
        winwait, Darkness Within, will install
        ControlClick, TNewButton1
        winwait, Darkness, License
        ControlClick, TNewRadioButton1
        ControlClick, TNewButton2
        winwait, Darkness, Location
        ControlClick, TNewButton3
        winwait, Darkness, shortcuts
        ControlClick, TNewButton4
        winwait, Darkness, additional
        ControlClick, TNewButton4
        winwait, Darkness, Ready to Install
        ControlClick, TNewButton4
        winwait, PhysX, License
        ControlClick, Button3
        ControlClick, Button4
        winwait, PhysX, successfully
        ControlClick, Button1
        winwait, Darkness
        ControlClick, TNewListBoxButton1
        ControlClick, TNewButton4
    "
    cd "$olddir"

    if workaround_wine_bug 23041
    then
        sh "$WINETRICKS" -q d3dx9_36
    fi

    # you have to cd to the directory containing DarkLineage.exe before running it
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Iceberg Interactive\Darkness Within 2 Demo"
"DarkLineage.exe"
__EOF__
}

#----------------------------------------------------------------

verblist_add daytona_usa_evolutions  "Daytona USA Evolutions (Sega, 1997)" daytonev.exe

# http://appdb.winehq.org/objectManager.php?sClass=application&iId=1136
load_daytona_usa_evolutions() {
    # Refuses to run on anything newer...
    sh "$WINETRICKS" -q win98
    
    load_autohotkey    
    
    download $PACKAGE http://www2.sega.co.jp/download/pc/daytonae/daytonev.exe 65c51766e01b582c15200afb0fd569e0ec5ca1ac
    
    # Installer starts by extracting files, but doesn't seem to be a zip file or a cab file. I tried a few cli arguments,
    # but had no luck. It's only 60 MB extracted, so just extract it fresh each time.
    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, daytonev.exe
        winwait, WinSFX32 V2.16.2.6, Install &Directory:
        sleep 1000
        controlclick, Button2, WinSFX32 V2.16.2.6, Install &Directory:
        loop
        {
            ifwinexist, WinSFX32 V2.16.2.6, Install &Directory:
                sleep 5000
            else
                break
        }
    "
    cd daytonev
    # There's a lot of unknown characters (presumably Japanese). Should this require user to run in
    # a Japanese locale?
    ahk_do "
        SetTitleMatchMode, 2
        run, Setup.exe
        winwait, Welcome, ???? DAYTONA USA Evolution ? !
        sleep 1000
        controlclick, Button1, Welcome, ???? DAYTONA USA Evolution ? !
        winwait, ???????????, ???????? PATH ??????????
        sleep 1000
        controlclick, Button1, ???????????, ???????? PATH ??????????
        winwait, Setup, ??????????????????????
        sleep 1000
        controlclick, Button1, Setup, ??????????????????????
        winwait, DirectX Install
        sleep 1000
        ; Damned if you do, damned if you don't...directx install fails if you attempt install, but if you don't, 'joystick.reg setup' fails.
        controlclick, Button2, DirectX Install
        sleep 1000
        winwait, Setup, Joystick.reg setup failed.
        sleep 1000
        controlclick, Button1, Setup, Joystick.reg setup failed.
        winwait, Setup, ???????????????
        sleep 1000
        controlclick, Button1, Setup, ???????????????
    "
    cd "$olddir"

    warn "Gives an error when closing the game, seems safe to ignore."

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$DRIVE_C\SEGA\DAYTONA USA Evolution Demo CD"
"DAYTONA USA Evolution Demo CD.exe"
__EOF__

}

#----------------------------------------------------------------

verblist_add dc2ba     "Doras Carnival 2: Boardwalk Adventure (Nickelodeon, 2008)" InstallDorasCarnival2BoardwalkAdventure.exe
load_dc2ba() {
    load_autohotkey

    # http://www.nickjr.com/games/p-doras-carnival-2-adventure.jhtml
    download $PACKAGE http://downloadcdn.shockwave.com/pub/doras-carnival-2-boardwalk-adventure/InstallDorasCarnival2BoardwalkAdventure.exe a02559c4d8236581f2ee0e51a1a11f67a901eaba
    
    if workaround_wine_bug 23749
    then
        sh "$WINETRICKS" -q ie6
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run InstallDorasCarnival2BoardwalkAdventure.exe
        winwait, Welcome
        sleep 1000
        controlclick, Button1, Welcome
        sleep 1000
        winwait, End User License
        sleep 1000
        controlclick, Button1, End User License
        winwait, Choose Destination Location
        sleep 1000
        controlclick, Button1, Choose Destination Location
        winwait, FREE Toolbar
        sleep 1000
        controlclick, Button5, FREE Toolbar
        sleep 1000
        controlclick, Button1, FREE Toolbar
        winwait, Start Installation
        sleep 1000
        controlclick, Button1, Start Installation
        winwait, Installation Complete
        sleep 1000
        controlclick, Button1, Installation Complete
    "
    sleep 5
    killall winefile.exe

cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Shockwave.com\\Dora's Carnival 2 - Boardwalk Adventure"
"Dora's Carnival 2 - Boardwalk Adventure.exe"
__EOF__

    # Workarounds needed by the game but not the installer should come at end of verb
    if workaround_wine_bug 13496
    then
        sh "$WINETRICKS" -q vcrun6
    fi
}

#----------------------------------------------------------------

verblist_add deadspace       "Dead Space (EA, 2008)" \
  abf250df77bfa96c74e7bcd0343d381a4f327a26.iso

load_deadspace() {
    load_autohotkey
    DEADSPACEKEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/abf250df77bfa96c74e7bcd0343d381a4f327a26.txt | tr -d -`

    if workaround_wine_bug 23324
    then
        msvcrun_me_harder="
            winwait, Microsoft
            controlclick, Button1
            "
    else
        msvcrun_me_harder=""
    fi

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/abf250df77bfa96c74e7bcd0343d381a4f327a26.iso
    ahk_do "
        SetTitleMatchMode, 2
        ; note: if this is the second run, the installer skips the registration code prompt
        run, ${ISO_MOUNT_LETTER}:EASetup.exe 
        winwait, Dead
        send {Enter}
        winwait, Dead, Registration Code
        send {RAW}$DEADSPACEKEY
        Sleep 1000
        controlclick, Button2
        $msvcrun_me_harder
        winwait, Setup, License
        Sleep 1000
        controlclick, Button1
        Sleep 1000
        send {Enter}
        winwait, Setup, License
        Sleep 1000
        controlclick, Button1
        Sleep 1000
        send {Enter}
        winwait, Setup, Destination
        Sleep 1000
        controlclick, Button1
        winwait, Setup, begin
        Sleep 1000
        controlclick, Button1
        winwait, Setup, Finish
        Sleep 1000
        controlclick, Button5
        controlclick, Button1
    "
    iso_umount

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Electronic Arts\\Dead Space"
Dead Space.exe
__EOF__
}


#----------------------------------------------------------------

verblist_add diablo2       "Diablo II (Blizzard, 2000)" \
  e20efb1ea60e58b4a25275a00571aabfe3ab4511.iso \
  51e2c630d5dd017e6168a8cf3ee24e39010316d9.iso \
  382ea98f270e39855b558b8fac0d609712a54ae8.iso \
  e20efb1ea60e58b4a25275a00571aabfe3ab4511.iso

load_diablo2() {
    warn "You must have already done 'wisotool load=YOURKEY' on the install disc, and 'wisotool load' on the other two discs." 
    load_autohotkey
    download diablo2 http://ftp.blizzard.com/pub/diablo2/patches/PC/D2Patch_113c.exe c78761bfb06999a9788f25a23a1ed30260ffb8ab

    # Force clean-ish install
    test -d "$programfilesdir_unix/Diablo II" && rm -rf "$programfilesdir_unix/Diablo II"

    # Get user's key
    DIABLOIIKEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/e20efb1ea60e58b4a25275a00571aabfe3ab4511.txt | tr -d -`

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/e20efb1ea60e58b4a25275a00571aabfe3ab4511.iso
    ahk_do "
        run ${ISO_MOUNT_LETTER}:setup.exe
        winwait, Diablo II Setup
        send {i}
        winwait, Choose Installation Size
        send {u}
        send {Enter}
        send {Raw}$USERNAME
        send {Tab}{Raw}$DIABLOIIKEY
        send {Enter}
        winwait, Diablo II - choose install directory
        send {Enter}
        winwait, Desktop Shortcut
        send {N}
        winwait, Insert Disc"
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/51e2c630d5dd017e6168a8cf3ee24e39010316d9.iso
    # Needed by patch 1.13c to avoid disc swapping
    cp "$ISO_MOUNT_ROOT"/d2music.mpq "$programfilesdir_unix/Diablo II/"
    ahk_do "
        send, {Enter}
        Sleep 1000
        winwait, Insert Disc"
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/382ea98f270e39855b558b8fac0d609712a54ae8.iso
    ahk_do "
        send, {Enter}
        Sleep 1000
        winwait, Insert Disc"
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/e20efb1ea60e58b4a25275a00571aabfe3ab4511.iso
    ahk_do "
        send, {Enter}
        Sleep 1000
        winwait, View ReadMe?
        ControlClick &No, View ReadMe?
        winwait, Register Diablo II Electronically?
        send {N}
        winwait, Diablo II Setup - Video Test
        ControlClick &Cancel, Diablo II Setup - Video Test
        winclose, Diablo II Setup"
    iso_umount

    try "$WINE" "$WISOTOOL_CACHE"/diablo2/D2Patch_113c.exe
    ahk_do "
        winwait Blizzard Updater v2.72
        send {Enter}
        winwait Diablo II
        ControlClick &Cancel, Diablo II"
    # Dagnabbit, the darn updater starts the game after it updates, no matter what I do?
    killall "Game.exe"

    warn "When starting the game, be patient, wait until the menu appears.  The game seems to hang if it looses focus, see bug 14456, you may need to set winecfg to virtual desktop."

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Diablo II"
"Diablo II.exe"
__EOF__
}

#----------------------------------------------------------------

verblist_add dragonage     "Dragon Age: Origins (Bioware / EA, 2009)" 705a6b06d0dd807bf62b4391d278649d728ebda4.iso

load_dragonage() {
    load_autohotkey

    # Get user's key
    DRAGONAGEKEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/705a6b06d0dd807bf62b4391d278649d728ebda4.txt | tr -d -`

    # Installer has a non-fatal crash on exit, so ignore it.
    sh "$WINETRICKS" -q nocrashdialog physx vcrun2005
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/705a6b06d0dd807bf62b4391d278649d728ebda4.iso

    ahk_do "
        Run, ${ISO_MOUNT_LETTER}:Setup.exe
        SetTitleMatchMode, 2
        winwait, Installer Language
        send {Enter}
        winwait, Dragon Age: Origins Setup
        ControlClick Next, Dragon Age: Origins Setup
        winwait, Dragon Age: Origins Setup, End User License
        sleep 1000
        ;ControlClick Button4, Dragon Age: Origins Setup  ; agree
        send {Tab}a  ; agree
        ;ControlClick I agree, Dragon Age: Origins Setup
        send {Enter} ; continue
        SetTitleMatchMode, 1
        winwait, Dragon Age: Origins, Registration
        send $DRAGONAGEKEY
        send {Enter}
        winwait, Dragon Age: Origins Setup, Install Type
        Sleep 1000
        send {Enter}
        loop 100
        {
            IfWinExist, Dragon Age: Origins Setup
                sleep 60000
        }
        exit 0
    "
    iso_umount
    
    if workaround_wine_bug 22307
    then
        warn "Turn off frame buffer effects to avoid blurry cut scenes.  See http://bugs.winehq.org/show_bug.cgi?id=22307"
    fi
    if workaround_wine_bug 22383
    then
        try "$WINETRICKS" -q strictdrawordering=enabled
    fi
    if workaround_wine_bug 23730
    then
        warn "Run with WINEDEBUG=-all to reduce flickering."
    fi
    if workaround_wine_bug 23081
    then
        warn "If you still see flickering, try applying the patch from http://bugs.winehq.org/show_bug.cgi?id=23081"
    fi

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Dragon Age"
bin_ship\\daorigins.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add fallout3_goty     "Fallout 3: Game of the Year Edition (Bethesda, 2009)" 379e2daa9bdd1aaf1cb152c1d9f8181f8f24e01b.iso \
                                f131e45dba66ed2c98dd7a1e04cc1114b7c5e4b6.iso

load_fallout3_goty() {
# http://appdb.winehq.org/objectManager.php?sClass=version&iId=14322
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/379e2daa9bdd1aaf1cb152c1d9f8181f8f24e01b.iso

    ahk_do "
        Run, ${ISO_MOUNT_LETTER}:Setup.exe
        SetTitleMatchMode, 2        
        winwait, Fallout 3 - InstallShield Wizard, Welcome to the InstallShield Wizard for Fallout 3
        sleep 1000
        controlclick, Button1, Fallout 3 - InstallShield Wizard, Welcome to the InstallShield Wizard for Fallout 3
        winwait, Fallout 3 - InstallShield Wizard, Please read the following license agreement carefully.
        sleep 1000
        controlclick, Button3, Fallout 3 - InstallShield Wizard, Please read the following license agreement carefully.
        sleep 1000
        controlclick, Button1, Fallout 3 - InstallShield Wizard, Please read the following license agreement carefully.
        winwait, Fallout 3 - InstallShield Wizard, Please select a setup type.
        sleep 1000
        controlclick, Button4, Fallout 3 - InstallShield Wizard, Please select a setup type.
        winwait, Fallout 3 - InstallShield Wizard, Click Install to begin the installation.
        sleep 1000
        controlclick, Button1, Fallout 3 - InstallShield Wizard, Click Install to begin the installation.
        winwait, Fallout 3 - InstallShield Wizard, InstallShield Wizard Complete
        sleep 1000
        controlclick, Button1, Fallout 3 - InstallShield Wizard, InstallShield Wizard Complete
        sleep 1000
        controlclick, Button2, Fallout 3 - InstallShield Wizard, InstallShield Wizard Complete
        sleep 1000
        controlclick, Button3, Fallout 3 - InstallShield Wizard, InstallShield Wizard Complete
    "

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/f131e45dba66ed2c98dd7a1e04cc1114b7c5e4b6.iso

    ahk_do "
        Run, ${ISO_MOUNT_LETTER}:EN_Fallout_3_DLC.EXE
        SetTitleMatchMode, 2
        winwait, Fallout 3 - DLC EN - InstallShield Wizard, Welcome to the InstallShield Wizard for Fallout 3 - DLC EN
        sleep 1000
        controlclick, Button1, Fallout 3 - DLC EN - InstallShield Wizard, Welcome to the InstallShield Wizard for Fallout 3 - DLC EN
        winwait, Fallout 3 - DLC EN - InstallShield Wizard, Please read the following license agreement carefully.
        sleep 1000
        controlclick, Button5, Fallout 3 - DLC EN - InstallShield Wizard, Please read the following license agreement carefully.
        sleep 1000
        controlclick, Button2, Fallout 3 - DLC EN - InstallShield Wizard, Please read the following license agreement carefully.
        winwait, Fallout 3 - DLC EN - InstallShield Wizard, Click Install to begin the installation.
        sleep 1000
        controlclick, Button1, Fallout 3 - DLC EN - InstallShield Wizard, Click Install to begin the installation.
        winwait, Fallout 3 - DLC EN - InstallShield Wizard, InstallShield Wizard Complete
        sleep 1000
        controlclick, Button4, Fallout 3 - DLC EN - InstallShield Wizard, InstallShield Wizard Complete
    "
  
    if workaround_wine_bug 23532
    then
        try "$WINETRICKS" -q xlive
    fi
    
cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Bethesda Softworks\\Fallout 3"
"Fallout3.exe"
__EOF__

}

#----------------------------------------------------------------

verblist_add fifa10     "Fifa 10 (EA, 2009)" 2038b86319862e1177912949e9f826f333571c48.iso 

load_fifa10() {
# http://appdb.winehq.org/objectManager.php?sClass=version&iId=14322
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/2038b86319862e1177912949e9f826f333571c48.iso

    # Get user's key
    fifakey=`cat "$WISOTOOL_CACHE"/$PACKAGE/2038b86319862e1177912949e9f826f333571c48.txt | tr -d -`

    if workaround_wine_bug 23433 'wine-1.2-422*|wine-1.2.*'
    then
        fifatitle="DisplayName from default.wxl"
    else
        # FIXME: What is it on Windows?
        fifatitle="FIFA 10"
    fi
    

    ahk_do "
        Run, ${ISO_MOUNT_LETTER}:AutoRun.exe
        SetTitleMatchMode, 2        
        winwait, FIFA 10, View the readme file
        sleep 1000
        controlclick, Button1, FIFA 10, View the readme file
        winwait, FIFA 10, Please enter the entire Registration Code found either
        sleep 1000
        send $fifakey
        send {Enter}
        winwait, Microsoft Visual C++ 2005, Please read the following license agreement
        sleep 1000
        controlclick, Button1, Microsoft Visual C++ 2005, Please read the following license agreement
        winwait, $fifatitle, I &accept the terms in the End User License Agreement
        sleep 1000
        controlclick, Button1, $fifatitle, I &accept the terms in the End User License Agreement
        sleep 1000
        controlclick, Button3, $fifatitle, I &accept the terms in the End User License Agreement
        ; There are two license agreements...one is for Directx
        winwait, $fifatitle, I &accept the terms in the End User License Agreement
        sleep 1000
        controlclick, Button1, $fifatitle, I &accept the terms in the End User License Agreement
        sleep 1000
        controlclick, Button3, $fifatitle, I &accept the terms in the End User License Agreement
        winwait, $fifatitle, Ready to install $fifatitle
        sleep 1000
        controlclick, Button1, $fifatitle, Ready to install $fifatitle
        winwait, $fifatitle, Click the Finish button to exit the Setup Wizard.
        sleep 1000
        controlclick, Button5, $fifatitle, Click the Finish button to exit the Setup Wizard.
        sleep 1000
        controlclick, Button1, $fifatitle, Click the Finish button to exit the Setup Wizard.
        winwait, Product Registration, Please log into your EA Master Account to continue.
        sleep 1000
        controlclick, Button14, Product Registration, Please log into your EA Master Account to continue.
    "

cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\EA Sports\\FIFA 10"
"FIFA10.exe"
__EOF__

}

#----------------------------------------------------------------
 

verblist_add fifaonline3_beta    "FIFA Online 3 Beta (EA Sports, 2010) [download]" FIFAOnlineSetup.exe

load_fifaonline3_beta()
{
    load_autohotkey
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/FIFAOnlineSetup.exe"
    then
        mkdir -p "$WISOTOOL_CACHE"/$PACKAGE
        die "Download the FIFAOnlineSetup.exe from http://fifa-online.easports.com/web/beta/welcome \
	     and place it in $WISOTOOL_CACHE/$PACKAGE"
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, FIFAOnlineSetup.exe
        winwait, C++, License
        controlclick, Yes
        winwait, FIFA, Testing Agreement
        controlclick, Button1
        controlclick, Button3
        winwait, FIFA, Punk
        controlclick, Button1
        controlclick, Button3
        winwait, FIFA, Destination
        controlclick, Button1
        winwait, Setup, Please wait
        sleep 1000
        winwaitclose, Setup, Please wait
        sleep 10000
        send {Right}
        sleep 1000
        send {Space}
        sleep 1000
        send {Right}
        sleep 1000
        send {Space}
    "
    # Wait for download to finish and game to start
    while [ `ps a | grep NFE.exe | grep -v grep | wc -l` != "1" ]
    do
        sleep 5
    done

    # Dont kill game immediately
    sleep 10
    killall "NFE.exe"

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
c:
cd \Program Files\\EA Sports\\FIFA Online
Launch.exe
__EOF__

}

#----------------------------------------------------------------
 
verblist_add fifa10_demo     "Fifa 10 Demo (EA, 2009)" fifa10_pc_demo_ec.exe

load_fifa10_demo() {
    load_autohotkey
    
    download $PACKAGE "http://gamedaily.newaol.com/pub/fifa10_pc_demo_ec.exe" 96200d4962fd6c34715c448ba22f00edd3d70cd6
    
    # The installer is a self extracting rar file. Make cleanups easy by using $WISOTOOL_TMP
    mkdir "$WISOTOOL_TMP/fifa10"
    cd "$WISOTOOL_TMP/fifa10"

    if workaround_wine_bug 23433 'wine-1.2-422*|wine-1.2.*'
    then
        fifatitle="DisplayName from default.wxl"
    else
        fifatitle="FIFA 10 - Demo"
    fi

    mkdir -p "$WISOTOOL_TMP/$PACKAGE"
    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        Run fifa10_pc_demo_ec.exe
        winwait, FIFA 10 PC Demo
        send $WISOTOOL_TMP_WIN\\${PACKAGE}{ENTER}
        winwait, FIFA 10 - Demo, View the readme file
        sleep 1000
        controlclick, Button1, FIFA 10 - Demo, View the readme file
        sleep 1000
        ; FIXME: make this block optional so we dont hang if wine vc2005 runtime passes the check and the game does not show this dialog
        winwait, Microsoft Visual C++ 2005 Redistributable Package (x86)
        sleep 1000
        controlclick, Button1, Microsoft Visual C++ 2005 Redistributable Package (x86)
        sleep 1000
        winwait, $fifatitle Setup, I &accept the terms in the End User License Agreement
        sleep 1000
        controlclick, Button1, $fifatitle Setup, Please read the End User License Agreement for $fifatitle
        sleep 1000
        controlclick, Button3, $fifatitle Setup, Please read the End User License Agreement for $fifatitle
        sleep 1000
        winwait, $fifatitle Setup, Please read the following End User License Agreement carefully
        sleep 1000
        controlclick, Button1, $fifatitle Setup, Please read the following End User License Agreement carefully
        sleep 1000
        controlclick, Button3, $fifatitle Setup, Please read the following End User License Agreement carefully
        sleep 1000
        winwait, $fifatitle Setup, Ready to install $fifatitle
        sleep 1000
        controlclick, Button1, $fifatitle Setup, Ready to install $fifatitle
        ; Very slow installer...
        winwait, $fifatitle Setup, Click the Finish button to exit the Setup Wizard.
        sleep 1000
        controlclick, Button1, $fifatitle Setup, Click the Finish button to exit the Setup Wizard.
    "
cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\EA Sports\\FIFA 10 - Demo"
FIFA10Demo.exe
__EOF__
}

#----------------------------------------------------------------
 
verblist_add ffxivbench "Final Fantasy XIV Benchmark (Square Enix, 2010)" FFXIVBenchmark.zip

load_ffxivbench() {
    download $PACKAGE http://uk.download.nvidia.com/nzone/international/benchmarks/ffxiv/FFXIVBenchmark.zip 9c2406540306575bdc738c439e59f54eb44304a8 
    
    cd "$programfilesdir_x86_unix"
    try unzip "$WISOTOOL_CACHE/$PACKAGE/FFXIVBenchmark.zip"

# Setup two batch files, one for high res, one for low res:
cat > FFXIVBenchmark/data/config.low <<__EOF__
[FFXIV_BENCHMARK]
LANGUAGE=1
CHARACTER=0
RESOLUTION=1
LOOP=0
__EOF__

cat > FFXIVBenchmark/data/config.high <<__EOF__
[FFXIV_BENCHMARK]
LANGUAGE=1
CHARACTER=0
RESOLUTION=0
LOOP=0
__EOF__

cat > "$DRIVE_C/run-$PACKAGE-low.bat" <<__EOF__
cd "$programfilesdir_x86_win\\FFXIVBenchmark\\data"
copy config.low config.ini /y
FFXivWinBenchmark.exe
__EOF__

cat > "$DRIVE_C/run-$PACKAGE-high.bat" <<__EOF__
cd "$programfilesdir_x86_win\\FFXIVBenchmark\\data"
copy config.high config.ini /y
FFXivWinBenchmark.exe
__EOF__

if workaround_wine_bug 22555
then
        try "$WINETRICKS" -q d3dx9_36
fi

}
    
#----------------------------------------------------------------
 
verblist_add gta_vc     "Grand Theft Auto: Vice City (Rockstar, 2003) " \
  e98c2d323dd0494989a844442586dc2d48fba8f9.iso \
  d31f5c35cc63d804a7ffdb212f550681b97ee5b3.iso

load_gta_vc() {
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/e98c2d323dd0494989a844442586dc2d48fba8f9.iso
    ahk_do "
    SetTitleMatchMode, 2
    Run, ${ISO_MOUNT_LETTER}:Setup.exe
    winwait, Choose Setup Language
    sleep 1000
    Send {enter}
    winwait, Grand Theft Auto Vice City, Welcome to the InstallShield Wizard
    sleep 1000
    Send {enter}
    winwait, Grand Theft Auto Vice City, License Agreement
    sleep 1000
    Send !a
    send {enter}
    winwait, Grand Theft Auto Vice City, Customer Information
    sleep 1000
    controlclick, edit1
    send $USERNAME
    send {tab}
    send company ; installer won't proceed without something here
    send {enter}
    winwait, Grand Theft Auto Vice City, Choose Destination Location
    sleep 1000
    controlclick, Button1
    winwait, Grand Theft Auto Vice City, Select Components
    sleep 1000
    controlclick, Button2
    winwait, Grand Theft Auto Vice City, Ready to Install the Program
    sleep 1000
    send {enter}
    winwait, Setup Needs The Next Disk, Please insert disk 2
    sleep 1000"
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/d31f5c35cc63d804a7ffdb212f550681b97ee5b3.iso
    ahk_do "
    sleep 1000
    send {enter}
    winwait, Grand Theft Auto Vice City, InstallShield Wizard Complete
    sleep 1000
    send {enter}
    "
    iso_umount
    
    if workaround_wine_bug 22414
    then
        try "$WINETRICKS" -q quartz
    fi
}

#----------------------------------------------------------------
 
verblist_add half_life_goty     "Half Life: Game of the Year Edition (Sierra, 2000) " \
  dc32c16bca6c19f14e3501e3be3e4a157ddbee20.iso

load_half_life_goty() {
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/dc32c16bca6c19f14e3501e3be3e4a157ddbee20.iso
    
    ahk_do "
    SetTitleMatchMode, 2
    Run, ${ISO_MOUNT_LETTER}:Setup.exe
    winwait, System Test, Did you hear the sound file?
    sleep 1000
    ControlClick, Button6, System Test, Did you hear the sound file?
    winwait, Welcome, Welcome to the Half-Life Setup program.  This program will install Half-Life on your computer.
    sleep 1000
    ControlClick, Button1, Welcome, Welcome to the Half-Life Setup program.  This program will install Half-Life on your computer.
    winwait, Software License Agreement, Please read the following License Agreement.  Press the PAGE DOWN key to see the rest of the agreement.
    sleep 1000
    ControlClick, Button2, Software License Agreement, Please read the following License Agreement.  Press the PAGE DOWN key to see the rest of the agreement.
    winwait, Choose Destination Location, Setup will install Half-Life in the following folder.
    sleep 1000
    ControlClick, Button1, Choose Destination Location, Setup will install Half-Life in the following folder.
    winwait, Install, Setup has placed the Sierra Utilities in your Start Menu.
    sleep 1000
    ControlClick, Button1, Install, Setup has placed the Sierra Utilities in your Start Menu.
    winwait, Install, Setup has determined that there may be updates to your product available.
    sleep 1000
    ControlClick, Button7, Install, Setup has determined that there may be updates to your product available.
    winwait, Install, Please Register Now!
    sleep 1000
    ControlClick, Button1, Install, Please Register Now!
    winwait, Choose Method of Registration, Please choose a registration method
    sleep 1000
    ControlClick, Button8, Choose Method of Registration, Please choose a registration method
    winwait, Select Components, Please ensure you are running the latest drivers appropriate for your hardware
    sleep 1000
    ControlClick, Button11, Select Components, Please ensure you are running the latest drivers appropriate for your hardware
    winwait, Setup Complete, Setup has finished installing Half-Life on your computer.
    sleep 1000
    ControlClick, Button1, Setup Complete, Setup has finished installing Half-Life on your computer.
    Sleep 1000
    ControlClick, Button4, Setup Complete, Setup has finished installing Half-Life on your computer.
    "
    
    # The key is put in on first run:
    HALF_LIFE_GOTY_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/dc32c16bca6c19f14e3501e3be3e4a157ddbee20.txt`
    cd $DRIVE_C/SIERRA/Half-Life
    
    # Forcefully closing the process later will screw up the screen resolution, so store the user's current resolution so we can restore it later:
    current_res=`xrandr -q | awk -F'current' -F',' 'NR==1 {gsub("( |current)","");print $2}'`

    # FIXME: Not sure how reliable the ahk_class designation is...
    ahk_do "
    Run, hl.exe
    winwait, ahk_class #32770
    sleep 1000
    ControlClick, Edit1, ahk_class #32770
    Send {RAW}$HALF_LIFE_GOTY_KEY
    sleep 1000
    ControlClick, Button1, ahk_class #32770
    sleep 5000
    ; I tried closing it the nice way, with either PostMessage or Win_close, but neither worked
    process, close, hl.exe
    "
    xrandr -s $current_res
}

#----------------------------------------------------------------

hbpdemoexe=Release_HBP_demo_PC_DD_DEMO_FINAL_348428.exe
verblist_add hphbp_demo    "Harry Potter & The Half Blood Prince Demo (EA, 2009) [download]" $hbpdemoexe

load_hphbp_demo()
{
    case "$LANG" in
    ""|"C") die "Harry Potter won't install in the Posix locale; please do 'export LANG=en_US.UTF-8' or something like that" ;;
    esac

    load_autohotkey
    
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/$hbpdemoexe"
    then
        download $PACKAGE http://largedownloads.ea.com/pub/demos/HarryPotter/Release_HBP_demo_PC_DD_DEMO_Final_348428.exe dadc1366c3b5e641454aa337ad82bc8c5082bad2
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, $hbpdemoexe
        winwait, Harry Potter, Install
        controlclick, Button1, Harry Potter
        winwait, Setup, License
        controlclick, Button1
        controlclick, Button3
        winwait, Setup, License
        controlclick, Button1
        controlclick, Button3
        winwait, Setup, Destination
        controlclick, Button1
        winwait, Setup, begin
        controlclick, Button1
        winwait, Setup, Finish
        controlclick, Button1
    "
    cd "$olddir"

    # Not sure I trust putting \U2122 in a batch file, so use a wild card to cd to the right dir.
    # Have to "cd pc" as next command, or the wildcard expansion fails on wine?
    # Have to be in the pc directory for the app to find its files.
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd $programfilesdir_x86_win\\Electronic Arts\\Harry Potter and the Half-Blood Prince* Demo
cd pc
hp6_demo.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add hphbp    "Harry Potter & The Half Blood Prince (EA, 2009)" 9590f4c4bf2d5e819014cd9b03a5d5408ae2cd7d.iso

load_hphbp()
{
    case "$LANG" in
    ""|"C") die "Harry Potter won't install in the Posix locale; please do 'export LANG=en_US.UTF-8' or something like that" ;;
    esac

    load_autohotkey
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/9590f4c4bf2d5e819014cd9b03a5d5408ae2cd7d.iso
    HPHBP_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/9590f4c4bf2d5e819014cd9b03a5d5408ae2cd7d.txt | tr -d -`
    ahk_do "
        SetTItleMatchMode, 2
        run, ${ISO_MOUNT_LETTER}:EASetup.exe
        winwait, Harry Potter
        send {RAW}$HPHBP_KEY
        controlclick, Button2
        winwait, Setup, License
        controlclick, Button1
        controlclick, Button3
        winwait, Setup, License
        controlclick, Button1
        controlclick, Button3
        winwait, Setup, Destination
        controlclick, Button1
        winwait, Setup, begin
        controlclick, Button1
        winwait, Setup, Finish
        controlclick, Button1
    "
    $WINESERVER -w
    iso_umount
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd $programfilesdir_x86_win\Electronic Arts\Harry Potter and the Half-Blood Prince*
cd pc
hp6.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add hegemonypom_demo    "Hegemony: Philip of Macedon Demo (Longbow Games, 2010) [download]" Hegemony_Philip_of_Macedon_Installer.exe 

load_hegemonypom_demo()
{
    load_autohotkey

    mkdir -p "$WISOTOOL_CACHE/$PACKAGE"
    cd "$WISOTOOL_CACHE/$PACKAGE"

    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/Hegemony_Philip_of_Macedon_Installer.exe"
    then
        download $PACKAGE http://www.longbowgames.com/downloads/Hegemony%20Philip%20of%20Macedon%20Installer.exe d3d2aa020d38b594d112360ae40871662d35dea4
        # Get rid of spaces in exe name, since download leaves them as %20's, and ahk_do might not make it easy to use quotes
        mv Hegemony* Hegemony_Philip_of_Macedon_Installer.exe
    fi

    ahk_do "
        SetTitleMatchMode, 2
        run, Hegemony_Philip_of_Macedon_Installer.exe
        winwait, Hegemony, installation
        controlclick, Button2
        winwait, Hegemony, License
        controlclick, Button2
        winwait, Hegemony, Components
        controlclick, Button2
        winwait, Hegemony, Install Location
        controlclick, Button2
        winwait, Hegemony, shortcuts
        controlclick, Button2
        winwait, Hegemony, has been installed
        controlclick, Button4
        controlclick, Button2
    "
    cd "$olddir"
}

#----------------------------------------------------------------

verblist_add help     "How to use this tool"

load_help() {
    warn "If the game is not marked with {download} or {loaded} in the menu, you have to insert its disc and give the 'load' command before you can choose that game in the menu.  If the game has multiple discs, you have to do this for each disc."
    warn "If the game has an install key, you have to enter that when loading the first disc.  (You have to do that from the commandline, e.g. sh wisotool load=XXXX-YYYY-ZZZZ.)"
}

#----------------------------------------------------------------

honexe=HoNClient-1.0.0.1.exe
verblist_add hon "Heroes of Newerth (S2 Games, 2010) [download]" \
$honexe

load_hon()
{
    load_autohotkey

    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/$honexe"
    then
        download $PACKAGE http://dl2.heroesofnewerth.com/$honexe
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, $honexe
        winwait, Heroes of Newerth
        controlclick, Button2, Heroes of Newerth
        winwait, Heroes of Newerth, License
        controlclick, Button2, Heroes of Newerth, License
        winwait, Heroes of Newerth, Components
        controlclick, Button2, Heroes of Newerth, Components
        winwait, Heroes of Newerth, Install Location
        controlclick, Button2, Heroes of Newerth, Install Location
        winwait, Heroes of Newerth, Start Menu
        controlclick, Button2, Heroes of Newerth, Start Menu
        winwait, Heroes of Newerth, Finish
        controlclick, Button2, Heroes of Newerth, Finish
    "
    cd "$olddir"

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Heroes of Newerth"
hon.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add hod3_jp_demo "The House of the Dead 3 - Japanese - Demo (SEGA, 2005) [download]"  hod3_trial.exe

load_hod3_jp_demo() {
    load_autohotkey
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/hod3_trial.exe"
    then
        download $PACKAGE http://www2.sega.co.jp/download/pc/hod3/hod3_trial.exe f616ac945bcbb5b897d24f3ce568c0f528801d05
    fi
    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        ; Use slow matching because otherwise autohotkey cant find the 1-2-12 in the Asian text
        SetTitleMatchMode, slow
        run hod3_trial.exe
        winwait, THE HOUSE OF THE DEAD 3,Windows
        send {Enter}
        winwait, THE HOUSE OF THE DEAD 3,1-2-12
        Send {Up}
        Send {Space}
        send {Enter}
        winwait, THE HOUSE OF THE DEAD 3,SEGA
        send {Enter}
        winwaitclose
        winwait, THE HOUSE OF THE DEAD 3
        send {Enter}
        ; Installer crashes before putting up finished dialog, but app seems okay anyway
    "
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__
cd "$programfilesdir_x86_win\\SEGA\\THE HOUSE OF THE DEAD3_JP_TRIAL"
hod3launch.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add lhp_demo "LEGO Harry Potter Demo [Years 1-4] (Travellers Tales / WB, 2010) [download]" LEGOHarryPotterDEMO.exe

load_lhp_demo()
{
    load_autohotkey

    case "$LANG" in
    *UTF-8*) ;;
    *) die "This installer fails in non-utf-8 locales.  Try doing export LANG=en_US.UTF-8"
    esac

    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/LEGOHarryPotterDEMO.exe"
    then
        download $PACKAGE http://static.kidswb.com/legoharrypottergame/LEGOHarryPotterDEMO.exe bb0a30ad9a7cc51c80e1bb1f3eec22e6ccc1a706
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, LEGOHarryPotterDEMO.exe
        winwait, LEGO, language
        controlclick, Button1
        winwait, LEGO, License
        controlclick, Button1
        controlclick, Button2
        winwait, LEGO, installation method
        controlclick, Button2
        winwait, LEGO, Finish
        controlclick, Button1
    "
    cd "$olddir"

    if workaround_wine_bug 23397
    then
        warn "If you have sound problems, try switching to OSS sound in winecfg"
    fi

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\WB Games\\LEGO*"
LEGOHarryPotterDEMO.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add lotsn   "Launch of the Screaming Narwhal (Telltale Games / Lucasarts, 2009)" LaunchOfTheScreamingNarwhal_Setup.exe

load_lotsn()
{
    load_autohotkey

    if ! test -f "${WISOTOOL_CACHE}/${PACKAGE}/LaunchOfTheScreamingNarwhal_Setup.exe" 
    then
        download ${PACKAGE} http://www.telltalegames.com/demo/launchofthescreamingnarwhal 8a9292d89fd5e7efe58e63dcfc84a05bf08ff1d6 LaunchOfTheScreamingNarwhal_Setup.exe
    fi

    load_gecko

    cd "${WISOTOOL_CACHE}/${PACKAGE}"
    chmod +x LaunchOfTheScreamingNarwhal_Setup.exe
    ahk_do "
        SetTitleMatchMode, 2
        run, LaunchOfTheScreamingNarwhal_Setup.exe
        WinWait, Setup
        ControlClick Button2  ; Next
        WinWait, Setup, Checking DirectX
        ControlClick Button5  ; Don't check
        ControlClick Button2  ; Next
        WinWait, Setup, License
        ControlClick Button2  ; Agree
        WinWait, Setup, Location
        ControlClick Button2  ; Install
        WinWait, Setup, has been installed
        ControlClick Button4  ; uncheck Play Now
        ControlClick Button2  ; Finish
        WinWaitClose
    "
    cd "${olddir}"

    cat > "${DRIVE_C}/run-${PACKAGE}.bat" << __EOF__
cd "${programfilesdir_x86_win}\\Telltale Games\\Tales of Monkey Island\\Launch of the Screaming Narwhal"
MonkeyIsland101.exe
__EOF__

    if workaround_wine_bug 22161
    then
        # Crashes on startup without this
        sh "$WINETRICKS" -q d3dx9_36
    fi
}

#----------------------------------------------------------------

verblist_add lswcs "Lego Star Wars Complete Saga (Lucasarts, 2009)" dc5db10e2ad2892ba40015d3856d1d29dc55893a.iso

load_lswcs() {
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/dc5db10e2ad2892ba40015d3856d1d29dc55893a.iso
    ahk_do "
        run ${ISO_MOUNT_LETTER}:setup.exe
        SetTitleMatchMode, 2
        winwait, Choose Setup Language
        send {Enter}
        winwait, LEGO, License Agreement
	send a{Enter}
        winwait, LEGO, method
        ControlClick Easy Installation
        sleep 1000
        winwaitclose, LEGO
    "
    # Installer crashes at end (http://bugs.winehq.org/show_bug.cgi?id=22529) but this doesn't seem to hurt.
    # Wait for all processes to exit, else unmount will fail
    # FIXME: use right wineserver
    wineserver -w
    iso_umount

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\LucasArts\\LEGO Star Wars - The Complete Saga"
LEGOStarWarsSaga.exe
__EOF__

    warn "This game is copy-protected, and requires the real disc in a real drive to run."
}

#----------------------------------------------------------------

# Note: may require load_harder.  Result may vary in length and checksum.

verblist_add manhole     "The Manhole Masterpiece Edition (Cyan, 1994)" \
  39aea1267c2b2b22a7d5c1e9f86ea1f4461457e3.iso

load_manhole() {
    cd $WISOTOOL_TMP

    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/39aea1267c2b2b22a7d5c1e9f86ea1f4461457e3.iso
    mkdir -p "$DRIVE_C"/manhole
    try cp -r "$ISO_MOUNT_ROOT"/* "$DRIVE_C"/manhole
    iso_umount

    if workaround_wine_bug 22502
    then
        warn "Run with wine-1.0 to avoid crash on startup.  Also cancel when prompted to install Quicktime."
    fi
}

#----------------------------------------------------------------

verblist_add masseffect2       "Mass Effect 2 (BioWare, 2010)" \
  4b817d67c8b7e8e7bc33f8cb6047210ab554fef6.iso \
  49d1f9b85203049d52a8e34b92cd7d4b96e0c8be.iso

load_masseffect2() {
    load_autohotkey
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/4b817d67c8b7e8e7bc33f8cb6047210ab554fef6.iso
    ME2_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/4b817d67c8b7e8e7bc33f8cb6047210ab554fef6.txt | tr -d -`

    if workaround_wine_bug 22091
    then
        warn "Will probably hang at end of installer.  If a crash dialog comes up, you can kill it, it's done."
        #try sh "$WINETRICKS" -q nocrashdialog
    fi

    if workaround_wine_bug 23126
    then
        try sh "$WINETRICKS" -q vcrun2005
    fi
    if workaround_wine_bug 23125
    then
        try sh "$WINETRICKS" d3dx10
    fi
    if workaround_wine_bug 22919
    then
        try sh "$WINETRICKS" -q physx
    fi

    ahk_do "
        SetTitleMatchMode, 2
        run, ${ISO_MOUNT_LETTER}:Setup.exe
        winwait, Installer Language
        send {Enter}
        winwait, Mass Effect
        send {Enter}
        winwait, Mass Effect, License
        ControlClick, Button4
        ControlClick, Button2
        winwait, Mass Effect, Registration Code
        send {RAW}$ME2_KEY
        ControlClick, Button2
        winwait, Mass Effect, Install Type
        ControlClick, Button2
        winwait, Insert Disc
    "
    sleep 5
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/49d1f9b85203049d52a8e34b92cd7d4b96e0c8be.iso
    ahk_do "
        SetTitleMatchMode, 2
        winwait, Insert Disc
        ControlClick, Button4
        ; on windows, the first click doesn't seem to do it, so press enter, too
        sleep 1000
        send {Enter}
        ; Some installs may not get to this point due to an installer hang/crash (bug 22919)
        ; The hang/crash happens after the Physx install but does not seem to affect gameplay
        ; TODO: work around this by waiting in some other way for install to finish
        winwait, Mass Effect, Finish
        winkill, Mass Effect
    "
    if workaround_wine_bug 6971
    then
        echo "See http://appdb.winehq.org/objectManager.php?sClass=version&iId=19125 for info on how to patch wine to work around bug 6971"
    fi
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__
cd "$programfilesdir_x86_win\Mass Effect 2\Binaries"
MassEffect2.EXE
__EOF__

}

#----------------------------------------------------------------

verblist_add masseffect2_demo   "Mass Effect 2 (BioWare, 2010)" MassEffect2DemoEN.exe

load_masseffect2_demo() {
    load_autohotkey

    file="$WISOTOOL_CACHE/$PACKAGE/MassEffect2DemoEN.exe"
    if ! test -f "$file"
    then
        download ${PACKAGE} http://masseffect.bioware.com/cdn/A/ME2_DEMO/MassEffect2DemoEN.exe cda9a25387a98e29772b3ccdcf609f87188285e2
    fi

    if workaround_wine_bug 22091
    then
        warn "Will probably hang at end of installer.  If a crash dialog comes up, you can kill it, it's done."
        #try sh "$WINETRICKS" -q nocrashdialog
    fi

    if workaround_wine_bug 23126
    then
        try sh "$WINETRICKS" -q vcrun2005
    fi
    if workaround_wine_bug 23125
    then
        try sh "$WINETRICKS" d3dx10
    fi
    if workaround_wine_bug 22919
    then
        try sh "$WINETRICKS" -q physx
    fi

    mkdir -p "$WISOTOOL_TMP/$PACKAGE"
    # FIXME: use ln -fs on linux, cp on windows
    cp "$WISOTOOL_CACHE/$PACKAGE/MassEffect2DemoEN.exe" "$WISOTOOL_TMP"
    ahk_do "
        SetTitleMatchMode, 2
        run, $WISOTOOL_TMP_WIN\\MassEffect2DemoEN.exe
        winwait, Mass Effect 2 Demo
        Sleep 1000
        send {Enter}
        winwait, Mass Effect 2 Demo, conflicts
        Sleep 1000
        send {Enter}
        winwait, Mass Effect, License
        ControlClick, Button4
        ;ControlClick, Button2
        send {Enter}
        winwait, Mass Effect, Install Type
        ControlClick, Button2
        ; Some installs may not get to this point due to an installer hang/crash (bug 22919)
        ; The hang/crash happens after the Physx install but does not seem to affect gameplay
        ; TODO: work around this by waiting in some other way for install to finish
        winwait, Mass Effect 2 Demo, Finish
        winkill
    "
    if workaround_wine_bug 6971
    then
        echo "See http://appdb.winehq.org/objectManager.php?sClass=version&iId=19125 for info on how to patch wine to work around bug 6971"
    fi
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__
cd "$programfilesdir_x86_win\\Mass Effect 2 Demo\\Binaries"
MassEffect2.EXE
__EOF__

}

#----------------------------------------------------------------

verblist_add metro2033     "Metro 2033 (THQ, 2010)" 3de89e07449c2573cd4a334b0cd7da012a98f97c.iso

load_metro2033() {
    warn "You'll need to have STEAM_USER/STEAM_PASS set in your environment or in $WISOTOOL_CACHE. You'll also need your cd-key for Metro 2033 already added to your Steam Account."
    
    if [ ! "$STEAM_USER" -a ! -f "$WISOTOOL_CACHE"/STEAM_USER ]
    then
        die "You need to set STEAM_USER variable in your environment or put it in "$WISOTOOL_CACHE"/STEAM_USER"
    elif [ ! "$STEAM_USER" -a -f "$WISOTOOL_CACHE"/STEAM_USER ]
    then
        STEAM_USER=`cat "$WISOTOOL_CACHE"/STEAM_USER`
    fi

    if [ ! "$STEAM_PASS" -a ! -f "$WISOTOOL_CACHE"/STEAM_PASS ]
    then
        die "You need to set STEAM_PASS variable in your environment or put it in "$WISOTOOL_CACHE"/STEAM_PASS"
    elif [ ! "$STEAM_PASS" -a -f "$WISOTOOL_CACHE"/STEAM_PASS ]
    then
        STEAM_PASS=`cat "$WISOTOOL_CACHE"/STEAM_PASS`
    fi

    steam_dir="$programfilesdir_unix/Steam"

    load_autohotkey

    # Game uses Steam to install itself
    try sh $WINETRICKS -q steam

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/3de89e07449c2573cd4a334b0cd7da012a98f97c.iso
    METRO_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/3de89e07449c2573cd4a334b0cd7da012a98f97c.txt | tr -d -`

    cd "$steam_dir"

    # Run Steam, let it update. Then, in a separate thread, run the installer.
    ahk_do "
    SetTitleMatchMode, 2
    SetControlDelay -1
    run, Steam.exe -login $STEAM_USER $STEAM_PASS
    Winwait, Steam - Update News
    ; Close all windows, prevent conflicts with later controlclick's
    winclose, Steam - Update News
    winclose, Steam
    "
    
    ahk_do "
    Run, Steam.exe -install I:\\
    ; Install Metro 2033
    winwait, Install - Metro 2033
    send, {Enter}
    ; Shortcuts
    sleep 10000
    winwait, Install - Metro 2033
    send, {Enter}
    ; Installing...
    sleep 10000
    winwait, Install - Metro 2033
    send, {Enter}
    "
    
    # Wait for install to finish
    dl_log="$steam_dir/logs/download_log.txt"
        while true
        do
            grep "SetHasAllLocalContent(true) called for 43110" "$dl_log" && break
            sleep 15
        done

    ahk_do "
    send {Enter}
    sleep 1000
    run, Steam.exe -shutdown
    "

    warn "You'll need the Xinput2 patch from http://bugs2.winehq.org/attachment.cgi?id=29313 to be able to use the mouse."

cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Steam"
Steam.exe -login $STEAM_USER $STEAM_PASS -applaunch 43110
__EOF__

}

#----------------------------------------------------------------

verblist_add moh_beta    "Medal of Honor: Beta (EA, 2010) [download]" MOHMP_Beta_PC_Client_R2_550504_Installer.zip

load_moh_beta()
{
    load_autohotkey

    # Archive SHA1SUM 7585700202ec305017038be4f1cb8ee1b43c24a2
    file="$WISOTOOL_CACHE/$PACKAGE/MOHMP_Beta_PC_Client_R2_550504_Installer.zip"
    test -f "$file" || file="$WISOTOOL_CACHE/$PACKAGE/MOH-MPBetaClient_R2550504_Installer.zip"
    if ! test -f "$file"
    then
        mkdir -p "$WISOTOOL_CACHE/$PACKAGE"
        die "Download the beta from http://medalofhonor.com/beta or http://www.fileplanet.com/213429/210000/fileinfo/Medal-of-Honor---Multiplayer-Beta-Client and place in $WISOTOOL_CACHE/$PACKAGE"
    fi

    mkdir -p "$WISOTOOL_TMP/$PACKAGE"
    try unzip -o "$file" -d "$WISOTOOL_TMP/$PACKAGE"
    cd "$WISOTOOL_TMP/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, setup.exe 
        winwait, Medal of Honor, will install
        controlclick, Button1
        winwait, Medal of Honor, License
        controlclick, Button1
        controlclick, Button3
        winwait, Medal of Honor, License
        controlclick, Button1
        controlclick, Button3
        winwait, Medal of Honor, shortcuts
        controlclick, Button1
        winwait, Medal of Honor, Before continuing
        controlclick, Button1
        winwait, Medal of Honor, Finish
        controlclick, Button1
    "

    # Game defaults to Dx10. Must force DxVersion=9
    # This is identical to the BFBC2 bug. Should I file an app specific bug?
    if workaround_wine_bug 22762
    then
        cd "$DRIVE_C/users/$USERNAME/My Documents"
        if test -f "Medal of Honor MP Beta"/settings.ini
        then
            mv "Medal of Honor MP Beta"/settings.ini "Medal of Honor MP Beta"/oldsettings.ini
            sed 's,DxVersion=auto,DxVersion=9,;
                 s,Fullscreen=true,Fullscreen=false,' "Medal of Honor MP Beta"/oldsettings.ini > "Medal of Honor MP Beta"/settings.ini 
        else
            mkdir -p "Medal of Honor MP Beta"
            echo "[Graphics]" > "Medal of Honor MP Beta"/settings.ini
            echo "DxVersion=9" >> "Medal of Honor MP Beta"/settings.ini
        fi
    fi
    
    cd "$olddir"

    # fixme: Try to find a way to script this?
    warn "After you sign up at http://medalofhonor.com/beta, you will receive a beta key which you will need to enter the first time you run the game."
    
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Electronic Arts\\Medal of Honor MP Beta"
MoHMPGame.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add morrowind     "The Elder Scrolls III: Morrowind (Bethesda, 2002)" \
  c8368ed30d3f3fcd7fccf8bffcfcdf0a6d4cb68b.iso

load_morrowind() {
    cd $WISOTOOL_TMP
    # FIXME: Untested on Windows!

    # FIXME: Only supports the main installer, and the construction set (which follows automatically)
    # eventually should support the expansions as well
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/c8368ed30d3f3fcd7fccf8bffcfcdf0a6d4cb68b.iso
    ahk_do "
    SetTitleMatchMode, 2
    Run, ${ISO_MOUNT_LETTER}:Setup.exe
    winwait, The Elder Scrolls III:  Morrowind Setup, The Elder Scrolls III:  Morrowind (License Agreement)
    sleep 1000
    controlclick, Button2
    winwait, The Elder Scrolls III:  Morrowind Setup, Please read the following important information.
    sleep 1000
    controlclick, Button1
    winwait, The Elder Scrolls III:  Morrowind Setup, Setup will install Morrowind in the following folder.
    sleep 1000
    controlclick, Button1
    winwait, The Elder Scrolls III:  Morrowind Setup, Setup has enough information to start copying the program files.
    sleep 1000
    controlclick, Button1

    ; Then launched construction set setup
    winwait, The Elder Scrolls Construction Set Setup, The Elder Scrolls Construction Set (License Agreement)
    sleep 1000
    Controlclick, Button2
    ; No confirm screen? (FIXME: verify on windows)
    winwait, The Elder Scrolls Construction Set Setup, Setup has enough information to start copying the program files
    sleep 1000
    controlclick, Button1
    winwait, The Elder Scrolls Construction Set Setup, Setup has finished installing TES Construction Set on your computer.
    sleep 1000
    controlclick, Button4

    ; Exits the Construction set setup on its own, and goes back to main installer
    ; The text box is split into two lines separately, not using word wrap, hence the weird sentence..
    winwait, Question, Would you like to register Morrowind online now?  Make sure
    sleep 1000
    controlclick, Button2
    ; Sometimes finicky here, short sleep here works around it
    Sleep 10000
    winwait, The Elder Scrolls III:  Morrowind Setup, Setup has finished installing Morrowind on your computer.
    sleep 1000
    controlclick, Button4
    winwait, Information, You have installed Windows XP, which includes DirectX 8.1
    sleep 1000
    ControlClick, Button1
    
    exit 0"
    
    sleep 30s
    iso_umount
    cd "$olddir"
}

#----------------------------------------------------------------

mnbw_demo_exe=mb_warband_setup_1113.exe
verblist_add mnbw_demo "Mount & Blade Warband Demo (Taleworlds, 2010) [download]" ${mnbw_demo_exe}

load_mnbw_demo()
{
    load_autohotkey
    if ! test -f "${WISOTOOL_CACHE}/${PACKAGE}/${mnbw_demo_exe}" 
    then
        download ${PACKAGE} http://download.taleworlds.com/${mnbw_demo_exe}
    fi
    cd "${WISOTOOL_CACHE}/${PACKAGE}"
    chmod +x ${mnbw_demo_exe}
    ahk_do "
        SetTitleMatchMode, 2
        run, ${mnbw_demo_exe}
        WinWait, Warband
        ControlClick, Button2, Warband
        WinWait, Warband
        ControlClick, Button2, Warband
        WinWait, Warband, Finish
        ControlClick, Button4, Warband
        ControlClick, Button2, Warband
    "
    cd "${olddir}"
    cat > "${DRIVE_C}/run-${PACKAGE}.bat" << __EOF__
cd "${programfilesdir_x86_win}\\Mount&Blade Warband"
mb_warband.exe
__EOF__

}

#----------------------------------------------------------------

verblist_add nfsps_demo    "Need For Speed: Pro Street Demo (EA, 2007)" nfsps_pcdemo.exe

load_nfsps_demo()
{
    load_autohotkey
    
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/ps_pcdemo.exe"
    then
        download $PACKAGE http://largedownloads.ea.com/pub/demos/NFS/prostreet/nfsps_pcdemo.exe 9cf74563d28c29a40920e0c0644c2da6e8e2a888
    fi

    mkdir -p "$WISOTOOL_TMP/$PACKAGE"
    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, nfsps_pcdemo.exe
        winwait, ProStreet, folder
        send $WISOTOOL_TMP_WIN\\$PACKAGE
        controlclick, Button2
        winwait, ProStreet, View the readme
        controlclick, Button1
        winwait, ProStreet, License
        controlclick, Button1
        controlclick, Button3
        winwait, ProStreet, License
        controlclick, Button1
        controlclick, Button3
        winwait, ProStreet, Destination
        controlclick, Button1
        winwait, ProStreet, Ready
        controlclick, Button1
        winwait, ProStreet, Finish
        controlclick, Button1
        winwait, ProStreet, completed,
        controlclick, Button7
        controlclick, Button4
    "
    cd "$olddir"
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Electronic Arts\\Need for Speed ProStreet Demo"
nfsdemo.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add nfsshift    "Need For Speed: Shift (EA, 2009)" 83d3b7499742ccf77da11fc2613de422c6f30572.iso

load_nfsshift()
{
    load_autohotkey

    if workaround_wine_bug 23324
    then
        msvcrun_me_harder="
            winwait, Microsoft
            controlclick, Button1
            "
    else
        msvcrun_me_harder=""
    fi

    NFSSHIFT_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/83d3b7499742ccf77da11fc2613de422c6f30572.txt | tr -d -`
    iso_mount "$WISOTOOL_CACHE/$PACKAGE/83d3b7499742ccf77da11fc2613de422c6f30572.iso"
    ahk_do "
        SetTitleMatchMode, 2
        ; note: if this is the second run, the installer skips the registration code prompt
        run, ${ISO_MOUNT_LETTER}:EASetup.exe 
        ; Not sure which of two or three dialogs happens next
        loop
        {
            if winexist, SHIFT, Registration Code
            {
                send {RAW}$NFSSHIFT_KEY
                Sleep 1000
                ;controlclick, Button2
                send {Enter}
                break
            }
            if winexist, Microsoft
                break
            if winexist, Setup, License
                break
            sleep 1000
        }
        $msvcrun_me_harder
        winwait, Setup, License
        Sleep 1000
        ;controlclick, Button1 ; Accept   Doesn't work on vista
        send a  ; Accept
        Sleep 1000
        send {Enter}
        winwait, Setup, License
        Sleep 1000
        controlclick, Button1
        Sleep 1000
        send {Enter}
        winwait, Setup, Destination
        Sleep 1000
        controlclick, Button1
        winwait, Setup, begin
        Sleep 1000
        controlclick, Button1
        winwait, Setup, Finish
        Sleep 1000
        controlclick, Button5
        ;controlclick, Button1  ; Finish
        send {Enter}           ; Finish doesn't respond to click on vista?
    "
    iso_umount

    download $PACKAGE http://cdn.needforspeed.com/data/downloads/shift/SHIFTPCPATCHV1.02_NA.exe 3ec2bf46aeb223c369ffcb0b57c080fba67d5dd9

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run SHIFTPCPATCHV1.02_NA.exe
        WinWait Updating
        WinWaitClose Updating
    "

    # Need path on shift.exe, see bug 23319
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Electronic Arts\\Need for Speed SHIFT"
.\shift.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add nfsshift_demo    "Need For Speed: SHIFT Demo (EA, 2009) [download]" NFSSHIFTPCDEMO.exe

load_nfsshift_demo()
{
    load_autohotkey
    
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/NFSSHIFTPCDEMO.exe"
    then
        download $PACKAGE http://cdn.needforspeed.com/data/downloads/shift/NFSSHIFTPCDEMO.exe 7b267654d08c54f15813f2917d9d74ec40905db7
    fi

    mkdir -p "$WISOTOOL_TMP/$PACKAGE"
    # FIXME: use ln -s on Linux (in case user has run 'winetricks sandbox'),
    # but run the package from the cache on Windows
    cp "$WISOTOOL_CACHE/$PACKAGE/NFSSHIFTPCDEMO.exe" "$WISOTOOL_TMP"
    ahk_do "
        SetTitleMatchMode, 2
        SetTitleMatchMode, slow
        run, $WISOTOOL_TMP_WIN\\NFSSHIFTPCDEMO.exe
        winwait, WinRAR
        send $WISOTOOL_TMP_WIN\\$PACKAGE
        ControlClick, Button2
        winwait, SHIFT, View the readme
        controlclick, Button1
        ; Not all systems need the Visual C++ runtime
        loop
        {
            ifwinexist, Visual C++
            {
                controlclick, Button1
                break
            }
            ifwinexist, Setup, SHIFT Demo License
            {
                break
            }
            sleep 1000
        }
        winwait, Setup, SHIFT Demo License
        Sleep 1000
        send {Space}
        Sleep 1000
        send {Enter}
        winwait, Setup, DirectX
        Sleep 1000
        send {Space}
        Sleep 1000
        send {Enter}
        winwait, Setup, Destination
        Sleep 1000
        send {Enter}
        winwait, Setup, begin
        Sleep 1000
        controlclick, Button1
        winwait, Setup, Finish
        Sleep 1000
        controlclick, Button5
        controlclick, Button1
    "
    cd "$olddir"
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Electronic Arts\\Need for Speed SHIFT Demo"
shiftdemo.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add oblivion    "Elder Scrolls: Oblivion (Bethesda Game Studios, 2006)" 0c6826d55029e7b64150ebe804220284962657e1.iso

load_oblivion()
{
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/0c6826d55029e7b64150ebe804220284962657e1.iso

    ahk_do "
        SetTitleMatchMode, 2
        run, ${ISO_MOUNT_LETTER}:Setup.exe
        winwait, Oblivion, Welcome to the
        controlclick, Button1
        winwait, Oblivion, License Agreement
        controlclick, Button3
        controlclick, Button1
        winwait, Oblivion, Choose Destination
        controlclick, Button1
        winwait, Oblivion, Ready to Install
        controlclick, Button1
        winwait, Oblivion, Complete
        controlclick, Button1
        controlclick, Button2
        controlclick, Button3
        "
    iso_umount
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Bethesda Softworks Oblivion\\Oblivion"
Oblivion.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add orangebox     "Orange Box (Valve, 2007) " \
    976f67eec4b84331de8f6695272bc9192466da6a.iso \
    b86c9297cc4c56e98f8c3f3e489091ffa4b4a11d.iso

load_orangebox() {
    load_autohotkey

    test -f "$programfilesdir_x86_unix"/Steam/Steam.exe || try sh $WINETRICKS -q steam
    # Have to log in before you can install orangebox!
    $WINE 'c:\Program Files\Steam\Steam' -login $STEAMUSER $STEAMPW
    # Now, um, let it log in for a few seconds.  Anyone know how to tell when it's done?
    sleep 45

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/976f67eec4b84331de8f6695272bc9192466da6a.iso
    KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/976f67eec4b84331de8f6695272bc9192466da6a.txt | tr -d -`
    ahk_do "
        SetTitleMatchMode, 2
        Run, ${ISO_MOUNT_LETTER}:Setup.exe
        winwait, ahk_class #32770
        MouseMove, 300, 365
        ; user has to click Install; I can't script it!

        ; FIXME: only do these steps on first run; if you've
        ; already activated Orange Box on your account,
        ; these don't show up.
        ;winwait, Activation
        ;MouseMove, 60, 400
        ;Click
        ;Sleep 300
        ;setKeyDelay, 300
        ;sendEvent {Raw}$KEY
        ;; Skip notice about Team Fortress guest passes
        ;winwait, News
        ;MouseMove, 650, 800
        ;Click
        ;winwait, Activation
        ;MouseMove, 310, 565
        ;Click

        winwait, Install
        sendEvent {Enter}
        ; wait for "create start menu and install" question
        sleep 5000
        sendEvent {Enter}
        winwait, Insert
    "
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/b86c9297cc4c56e98f8c3f3e489091ffa4b4a11d.iso

    ahk_do "
        SetTitleMatchMode, 2
        Send {Enter}
        winwait, ahk_class MsiDialogCloseClass, Please insert
    "
    iso_umount

    # FIXME: how to tell when update is done?  Probably have to launch all games once 
    # the the commandline option to exit immediately.
}

#----------------------------------------------------------------

verblist_add pcmark04 "PC Mark 04 (Futuremark, 2004) [download]" PCMark04_v130_installer.exe

load_pcmark04() {
    load_autohotkey

    # http://www.futuremark.com/download/pcmark04/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/PCMark04_v130_installer.exe"
    then
        die "Sorry, you have to download PCMark04_v130_installer.exe yourself and put it in $WISOTOOL_CACHE/$PACKAGE/PCMark04_v130_installer.exe"
    fi

    warn "Please don't use mouse while this installer is running.  Sorry..."
    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run PCMark04_v130_installer.exe
        ; Skip past the two windows warning about WMP9 etc.
        WinWait, Information
        Send {Enter}
        WinWaitClose, Information
        WinWait, Information
        Send {Enter}

        WinWait ahk_class #32770, Welcome
        Send {Enter}
        WinWait, ahk_class #32770, License
        Send a ; Accept
        Send {Enter} ; Next
        Sleep 3000 ; Wait for Destination window
        Send {Enter}
        Sleep 3000 ; Wait for Install window
        Send {Enter}
        ; Wait for install to finish
        WinWait, PCMark04, Registration
        ; Purchase later
        ; This window won't activate any other way!
        MsgBox, 32, , Preparing your dungeon.  Why not enjoy a delicious slime mold while you wait?, 1
        Send {Enter}
        Sleep 3000
        ; Uncheck readme
        Send {Space}
        Send {Tab}
        Send {Tab}
        Send {Enter}
    "
    if workaround_wine_bug 22402
    then
        warn "You may need to apply the patch from bug 22402 to avoid a crash in the tumbling blocks test."
    fi

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Futuremark\PCMark04"
PCMark04
__EOF__
}

#----------------------------------------------------------------

verblist_add pcmark05 "PC Mark 05 (Futuremark, 2005) [download]" PCMark05_v120_1901.exe

load_pcmark05() {
    load_autohotkey

    # http://www.futuremark.com/download/pcmark05/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/PCMark05_v120_1901.exe"
    then
        download $PACKAGE http://www.bulletproofnerds.com/uploadedfiles/futuremark/PCMark05_v120_1901.exe 8636fce0e4023cd59bcf7f3e1a027e233ee81193
    fi

    warn "Don't use mouse while this installer is running.  Sorry..."
    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run PCMark05_v120_1901.exe
        ; Skip past the two windows warning about WMP10 etc.
        WinWait, Information
        Send {Enter}
        WinWaitClose, Information
        WinWait, Information
        Send {Enter}

        WinWait ahk_class #32770, Welcome
        Send {Enter}
        WinWait, ahk_class #32770, License
        Send a ; Accept
        Send {Enter} ; Next
        Sleep 3000 ; Wait for 2nd Welcome window
        Send {Enter}
        Sleep 3000 ; Wait for Destination window
        Send {Enter}
        Sleep 3000 ; Wait for Install window
        Send {Enter}
        ; Wait for install to finish
        WinWait, PCMark05, Registration
        ; Purchase later
        ; This window won't activate any other way!
        MsgBox, 32, , Preparing your dungeon.  Why not enjoy a delicious slime mold while you wait?, 1
        Send {Enter}
        Sleep 2000
        ; Uncheck readme
        Send {Space}
        Send {Tab}
        Send {Tab}
        Send {Enter}
    "

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Futuremark\PCMark05"
PCMark05
__EOF__
}

#----------------------------------------------------------------

# Not finished
#verblist_add passmark7 "Performance Test 7 (Passmark, 2010) [download]" petst.exe

load_passmark7() {
    load_autohotkey

    # http://www.passmark.com/download/pt_download.htm
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/petst.exe"
    then
        download $PACKAGE http://www.passmark.com/ftp/petst.exe 6d9db9c1bc53452cf7a2d3ad07a1195218095f8f
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        run petst.exe
    "
    warn "TODO: finish."
}

#----------------------------------------------------------------

verblist_add pscs5       "Photoshop CS5 Demo (Adobe, 2010)" \
    Photoshop_12_LS1.7z \
    Photoshop_12_LS1.exe


load_pscs5() {
    load_autohotkey
    try cd "$WISOTOOL_CACHE/$PACKAGE/"
    if [ ! -f "$WISOTOOL_CACHE/$PACKAGE/Photoshop_12_LS1.7z" ]
    then
        die "You must download Photoshop CS5 trial files and put them in $WISOTOOL_CACHE/$PACKAGE"
    else
        verify_sha1sum 0d8fac96f32963194add553b8ca072c40ca4b912 Photoshop_12_LS1.7z
    fi
    if [ ! -f "$WISOTOOL_CACHE/$PACKAGE/Photoshop_12_LS1.exe" ]
    then
        die "You must download Photoshop CS5 trial files and put them in $WISOTOOL_CACHE/$PACKAGE"
    else
        verify_sha1sum abbfeeef9348c79b6cdde5f8762f5c3f96d32f6e Photoshop_12_LS1.exe
    fi

    try Photoshop_12_LS1.exe /s /x /d .
    try cd "Adobe CS5"
    
    if workaround_wine_bug 22679
    then
        try sh "$WINETRICKS" -q msxml3
    fi

    warn "Try not to have anything else running, cs5 will complain if firefox is running, and the mouse clicks here are sensitive"
    
    # Doesn't have clickable buttons, resorting to window positions. May break on non standard dpi settings.    
    # Not sure how to detect when the window changes. They all have the same title, and no text is visible to AHK.
    # As a dirty workaround, may try detecting the color on the left side which shows the menu. The current step is darker
    # than the rest.
    ahk_do "
        SetTitleMatchMode, 2
        run Set-up.exe
        winwait, Adobe Photoshop CS5
        sleep 2000
        ControlClick, X750 Y550, Adobe Photoshop CS5
        sleep 2000
        winwait, Adobe Photoshop CS5
        sleep 2000
        ControlClick, X300 Y350, Adobe Photoshop CS5
        sleep 2000
        ControlClick, X700 Y340, Adobe Photoshop CS5
        Send, {Down}{Down}{Enter} ; Choose US English
        sleep 2000
        ControlClick, X750 Y550, Adobe Photoshop CS5
        sleep 2000
        winwait, Adobe Photoshop CS5
        sleep 2000
        ControlClick, X750 Y550, Adobe Photoshop CS5
        ; Installs in about 5 minutes here, but that's not a reliable number.
        ; The final window is indistinguishable from the previous, except that it has a button that the former does not.
        ; Exploit that to close the installer gracefully.
        Loop
            {
                ; Loop every 30 seconds while the installer window is present, and try to click the 'Done' button.
                ; If the window doesn't exist, installer is finally done.
                IfWinExist, Adobe Photoshop CS5
                {
                    ControlClick, X750 Y550, Adobe Photoshop CS5
                    Sleep 30000
                }
                else break
            }
    "
    try cd ..
    # Remove installer temp files:
    try cd "$WISOTOOL_CACHE/$PACKAGE/"
    try rm -rf "Photoshop CS5 Read Me.pdf" "Adobe CS5"
    try cd "$olddir"
}

verblist_add pscs5_pickle       "Photoshop CS5 Demo (Adobe, 2010)"

load_pscs5_pickle() {
    warn "This will tar up Photoshop CS5's files from a Windows install, along with needed registry entries, for use in wine with load_pscs5_unpickle()"
    
    if [ ! -d "$programfilesdir_x86_win/Adobe/Adobe Photoshop CS5/" ]
    then
        load_pscs5
    fi

    try cd "$WISOTOOL_TMP"

    # Setup a skeleton file structure:
    try rm -rf cs5_temp
    try mkdir -p cs5_temp/"Common Files"
    try mkdir -p cs5_temp/"Program Files"
    try mkdir -p cs5_temp/"userhome"

    try cd cs5_temp

    try sleep 1 # Potential race condition, caught me a couple times
    
    # First, the registry entries:
    try reg.exe export HKLM\\Software\\Adobe adobe_cs5.reg

    # Then the files:
    userprofile_unix="`cygpath $USERPROFILE`"
    system32_unix="`cygpath $WINDIR/system32`"

    try cd "Common Files"
    try cp -r "$programfilesdir_x86_unix/Common Files/Adobe" .
    try cd ../"Program Files"
    try cp -r "$programfilesdir_x86_unix/Adobe" .
    try cd ../userhome
    try cp -r "$userprofile_unix/Application Data/Adobe" .
    try cd ..
    try cp "$system32_unix/odbc32.dll" .
    try cp "$system32_unix/odbcint.dll" .
    
    try cd "$WISOTOOL_TMP"/cs5_temp
    try tar -c -f "$olddir/adobe_cs5.tar" *
    try cd ..
    try rm -rf cs5_temp
    try cd "$olddir"
    
}

verblist_add pscs5_unpickle       "Photoshop CS5 Demo (Adobe, 2010)" \
    adobe_cs5.tar

load_pscs5_unpickle() {
    warn "This will install Photoshop CS5's files from a Windows install made with pscs5_pickle()"
    
    # Install dependencies:
    try sh "$WINETRICKS" -q gdiplus ie6 msxml3 vcrun2005sp1 vcrun2008 

    try cd "$WISOTOOL_TMP"
    try tar xf "$WISOTOOL_CACHE/$PACKAGE/adobe_cs5.tar"
    try $WINE regedit adobe_cs5.reg
    try cd "$programfilesdir_x86_unix"
    try mv "$WISOTOOL_TMP/Program Files/Adobe" .
    try cd "Common Files"
    try mv "$WISOTOOL_TMP/Common Files/Adobe" .
    try cd "$DRIVE_C/users/$USER/Application Data/"
    try mv "$WISOTOOL_TMP/userhome"/* .
    try cd "$WINDIR/system32"
    try mv "$WISOTOOL_TMP/odbc32.dll" .
    try mv "$WISOTOOL_TMP/odbcint.dll" .
    try $WINE regsvr32 odbc32.dll
    try $WINE regsvr32 odbcint.dll
    
    warn "Do not report bugs to wine with an installation done this way. Wait until the installer bugs are fixed or have patches to workaround them!"
    warn "On the first run, it will tell you your trial has 0 days left. On the second run and after, it will say 30 days."
}

#----------------------------------------------------------------

verblist_add plantsvszombies "Plants vs. Zombies (PopCap Games, 2009) [download]" PlantsVsZombiesSetup.exe

load_plantsvszombies() {
    load_autohotkey

    if ! test -f "$WISOTOOL_CACHE/plantsvszombies/PlantsVsZombiesSetup.exe"
    then
        download plantsvszombies "http://downloads.popcap.com/www/popcap_downloads/PlantsVsZombiesSetup.exe" fcae7b8c63d9a5b5f6ed783232bc5f612fd5c963
    fi

    cd "$WISOTOOL_CACHE/plantsvszombies"
    ahk_do "
        run PlantsVsZombiesSetup.exe
        winwait, Plants vs. Zombies Installer
        send {Enter}
        winwait, Plants vs. Zombies License Agreement
        ControlClick Button1
        winwait, Plants vs. Zombies Installation Complete!
        send {Space}{Enter}
        ControlClick, x309 y278, Plants vs. Zombies Installation Complete!,,,, Pos
    "

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\PopCap Games\Plants vs. Zombies"
PlantsVsZombies
__EOF__
}

#----------------------------------------------------------------

verblist_add popsot "Prince of Persia Sands of Time (Ubisoft, 2003)" \
a55dc7459b0e8b40b49c16e62761932c90b6ede2.iso

load_popsot()
{
    load_autohotkey
    iso_mount "$WISOTOOL_CACHE/$PACKAGE/a55dc7459b0e8b40b49c16e62761932c90b6ede2.iso"
    ahk_do "
        SetTitleMatchMode, 2
        run, ${ISO_MOUNT_LETTER}:Setup.exe
        winwait, Prince of Persia, Language
        ControlClick, Button3
        winwait, Prince of Persia, Welcome
        ControlClick, Button1
        winwait, Prince of Persia, License
        ControlClick, Button3
        ControlClick, Button1
        winwait, Prince of Persia, Destination
        ControlClick, Button1
        winwait, Question, Proceed
        ControlClick, Button6
        winwait, Prince of Persia, Acrobat Reader
        ControlClick, Button2
        ControlClick, Button11
        winwait, Prince of Persia, Complete
        ControlClick, Button1
        ControlClick, Button4
        sleep 6000
        IfWinExist, register
        {
          ControlClick, OK, register
        }
    "
    iso_umount
}

#----------------------------------------------------------------

verblist_add popsot_demo "Prince of Persia Sands of Time Demo (Ubisoft, 2003)" \
POP_Demo_Eng.exe

load_popsot_demo()
{
    load_autohotkey
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/POP_Demo_Eng.exe" && ! test -f "$WISOTOOL_CACHE/$PACKAGE/pop_demo_eng.exe"
    then
        mkdir -p "$WISOTOOL_CACHE/$PACKAGE"
        warn "You must manually download the Prince of Persia Sands of Time Demo to $WISOTOOL_CACHE/$PACKAGE/pop_demo_eng.exe; expected sha1sum ed62f4da1f898c661ca09bd4e3a22e4a983a822b"
    fi
    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, POP_Demo_Eng.exe
        winwait, Prince of Persia, To continue
        ControlClick, Next, Prince of Persia, To continue
        winwait, Prince of Persia, License Agreement
        ControlClick, Button3, Prince of Persia
        ControlClick, Next, Prince of Persia
        sleep 1000
        IfWinExist, Minimum Configuration
        {
          send {Enter}
        }
        winwait, Prince of Persia, Choose Destination
        ControlClick, Next, Prince of Persia, Choose Destination
        winwait, Question
        ControlClick, Yes, Question
        winwait, Prince of Persia, Installing game
        winwaitclose, Prince of Persia, Installing game
        sleep 3000
        IfWinExist, Prince of Persia, Setup has detected
        {
          ControlClick, Button2, Prince of Persia, Setup has detected
          ControlClick, Next, Prince of Persia, Setup has detected
        }
        sleep 6000
        IfWinExist, register
        {
          ControlClick, OK, register
        }
        winwait, Prince of Persia, View the Readme
        ControlClick, Button1, Prince of Persia, View the Readme
        ControlClick, Finish, Prince of Persia, View the Readme 
    "
    cd "$olddir"
    warn "Once you're in the Prince of Persia game, turn off fog or you won't be able to see anything (see wine bug 17423 for explanation, but this isn't a wine bug)"
}

#----------------------------------------------------------------

verblist_add procycling08_demo "Pro Cycling Manager 2008 Demo (Cyanide, 2008) [download, broken in wine]" ProCyclingManager08_Demo.exe

load_procycling08_demo()
{
    load_autohotkey
    # FIXME sha1sum 008b91a16c388c9965faaeaaa8242409b9db56b9
    # FIXME homepage http://www.cycling-manager.com/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/ProCyclingManager08_Demo.exe"
    then
        mkdir -p "$WISOTOOL_CACHE/$PACKAGE"
        warn "Please download the game to $WISOTOOL_CACHE/$PACKAGE/ProCyclingManager08_Demo.exe from e.g. http://www.fileplanet.com/189566/download/Pro-Cycling-Manager---Tour-de-France-2008---Demo , sha1sum should be 008b91a16c388c9965faaeaaa8242409b9db56b9"
    fi

    cd $WISOTOOL_CACHE/$PACKAGE
    ahk_do "
        SetTitleMatchMode, 2
        run, ProCyclingManager08_Demo.exe
        winwait, Pro Cycling Manager, This will
        ControlClick, TButton1, Pro Cycling Manager, This will ; Next
        winwait, Pro Cycling, License
        ControlClick, TRadioButton1, Pro Cycling, License ; Accept License
        ControlClick, TButton2, Pro Cycling, License ; Next
        winwait, Pro Cycling, following folder
        ControlClick, TButton3, Pro Cycling, following folder ; Next
        winwait, Pro Cycling, shortcuts
        ControlClick, TButton4, Pro Cycling, shortcuts ; Next
        winwait, Pro Cycling, Click Install
        ControlClick, TButton4, Pro Cycling, Click Install ; Install
        winwait, Pro Cycling, finished
        ControlClick, TButton4, Pro Cycling,  finished ; Finish
    "
    cd "$olddir"

    if workaround_wine_bug 17512
    then
        warn "This game crashes under Wine; see http://bugs.winehq.org/show_bug.cgi?id=17512"
    fi
}

#----------------------------------------------------------------

verblist_add proevolution2010_demo "Pro Evolution Soccer 2010 Demo (Konami, 2009) [download]" PES2010_PC_DEMO_Setup.exe

load_proevolution2010_demo()
{
    # http://appdb.winehq.org/objectManager.php?sClass=version&iId=18148
    load_autohotkey
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/PES2010_PC_DEMO_Setup.exe"
    then
        download $PACKAGE http://gamedaily.newaol.com/pub/PES2010_PC_DEMO_Setup.exe a1c913c367f121adf5f6e4104c76ab48f8d9457e
    fi

    cd $WISOTOOL_CACHE/$PACKAGE
    ahk_do "
        SetTitleMatchMode, 2
        run, PES2010_PC_DEMO_Setup.exe
        winwait, Pro Evolution Soccer 2010 DEMO - InstallShield Wizard, WARNING: This program is protected
        sleep 1000
        ControlClick, Button1, Pro Evolution Soccer 2010 DEMO - InstallShield Wizard, WARNING: This program is protected ; Next
        winwait, Pro Evolution Soccer 2010 DEMO - InstallShield Wizard, Please read the following
        sleep 1000
        ControlClick, Button3, Pro Evolution Soccer 2010 DEMO - InstallShield Wizard, Please read the ; Accept license
        sleep 1000
        ControlClick, Button5, Pro Evolution Soccer 2010 DEMO - InstallShield Wizard, Please read the following license ; Next
        winwait, Pro Evolution Soccer 2010 DEMO - InstallShield Wizard, Click Next to install to this folder
        sleep 1000
        ControlClick, Button1, Pro Evolution Soccer 2010 DEMO - InstallShield Wizard, Click Next to install to this folder ; Next
        winwait, Pro Evolution Soccer 2010 DEMO - InstallShield Wizard, The wizard is ready to begin installation
        sleep 1000
        ControlClick, Button1, Pro Evolution Soccer 2010 DEMO - InstallShield Wizard, The wizard is ready to begin installation. ; Install
        winwait, Pro Evolution Soccer 2010 DEMO - InstallShield Wizard, InstallShield Wizard Completed
        sleep 1000
        ControlClick, Button1, Pro Evolution Soccer 2010 DEMO - InstallShield Wizard, InstallShield Wizard Completed ; Finished
    "
    cd "$olddir"

    if workaround_wine_bug 23104
    then
        try sh "$WINETRICKS" -q d3dx9
    fi
}



#----------------------------------------------------------------

verblist_add rom "Runes of Magic (Frogster Interactive, 2009) [download]" \
  Runes_of_Magic_3.0.1.2153.part1.exe \
  Runes_of_Magic_3.0.1.2153.part2.rar

load_rom()
{
    load_autohotkey

    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/Runes_of_Magic_3.0.1.2153.part1.exe" || ! test -f "$WISOTOOL_CACHE/$PACKAGE/Runes_of_Magic_3.0.1.2153.part2.rar"
    then
        download $PACKAGE http://frogster.vo.llnwd.net/o9/FOG/rom/Runes_of_Magic_3.0.1.2153_two.exe/Runes_of_Magic_3.0.1.2153.part1.exe 3263660262c6411f179e80c5ef0906c783d7bb08
        download $PACKAGE http://frogster.vo.llnwd.net/o9/FOG/rom/Runes_of_Magic_3.0.1.2153_two.exe/Runes_of_Magic_3.0.1.2153.part2.rar 569dee9c375fa50394958daa9f8d8a1b02bb9b11
    fi
    # manual updates from http://forum.runesofmagic.com/showthread.php?t=79267
    download $PACKAGE http://frogster.vo.llnwd.net/o9/patch/en/patch_3.0.1.2153.en_3.0.1.2172.en.exe 817391606fd1c05ad6194a06b21f6a5632cacf4f
    download $PACKAGE http://frogster.vo.llnwd.net/o9/patch/en/patch_3.0.1.2172.en_3.0.1.2175.en.exe ed120bc8140f8c3b2481a78f504a7a9e76c8642f
    download $PACKAGE http://frogster.vo.llnwd.net/o9/patch/en/patch_3.0.1.2175.en_3.0.1.2178.en.exe 012e679402f2165effbf2aaaffe41a5d9405d319
    download $PACKAGE http://frogster.vo.llnwd.net/o9/patch/en/patch_3.0.1.2178.en_3.0.1.2181.en.exe c449510566108dfc29882e6229cf716f232102df
    download $PACKAGE http://frogster.vo.llnwd.net/o9/patch/en/patch_3.0.1.2181.en_3.0.1.2192.en.exe d5afc10ff1126c3dabafa02b4681f411aa689c57
    download $PACKAGE http://frogster.vo.llnwd.net/o9/patch/en/patch_3.0.1.2192.en_3.0.1.2199.en.exe 542ac3b4d0fc4434aadfb784a46868f1815351da

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, Runes_of_Magic_3.0.1.2153.part1.exe
        winwait, Runes of Magic, This will install
        ControlClick, TNewButton1
        winwait, Runes of Magic, License
        ControlClick, TNewRadioButton1
        ControlClick, TNewButton2
        winwait, Runes of Magic, Destination
        ControlClick, TNewButton3
        winwait, Runes of Magic, shortcuts
        ControlClick, TNewButton4
        winwait, Runes of Magic, Additional Tasks
        ControlClick, TNewButton4
        winwait, Runes of Magic, Ready
        ControlClick, TNewButton4
        winwait, Runes of Magic, finished
        ControlClick, TNewCheckListBox1
        ControlClick, TNewButton4
	winwait, Territory
	send {Esc}
	; Don't let it autoupdate
	winkill
    "
    # FIXME: use right wineserver and/or find nicer way to finish
    wineserver -k

    cd "$WISOTOOL_CACHE"/$PACKAGE
    for patch in patch_*
    do
        ahk_do "
            run $patch
            SetTitleMatchMode, 2
            winwait, RomUpdate
            winwaitclose, RomUpdate
        "
    done

    if workaround_wine_bug 23217
    then
        try sh "$WINETRICKS" -q vcrun2005
    fi

    if workaround_wine_bug 22002
    then
        try sh "$WINETRICKS" -q ie6
    fi

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Runes of Magic"
"Runes of Magic.exe"
__EOF__

    cd "$olddir"
}

#----------------------------------------------------------------

verblist_add re5bench "Resident Evil 5 Benchmark (Capcom, 2009) [download]" nzd_ResidentEvil5_Benchmark.exe

load_re5bench() {
    load_autohotkey

    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/nzd_ResidentEvil5_Benchmark.exe"
    then
        download $PACKAGE http://download.nvidia.com/downloads/nZone/demos/nzd_ResidentEvil5_Benchmark.exe 041492b9af138f67e7acf97fbd8e926dda59ab12
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        run nzd_ResidentEvil5_Benchmark.exe
        WinWait ahk_class MsiDialogCloseClass 
        Sleep 1000
        Send {Enter}
        ; ControlClick Button1 ; Next.  Doesn't work?
        WinWait ahk_class MsiDialogCloseClass, License
        ControlClick Button3 ; Accept
        ControlClick Button5 ; Next
        WinWait ahk_class MsiDialogCloseClass, Destination
        ControlClick Button1 ; Next
        WinWait ahk_class MsiDialogCloseClass, Ready
        ControlClick Button1 ; Install
        WinWait ahk_class MsiDialogCloseClass, Completed
        ControlClick Button3 ; Uncheck Launch
        ControlClick Button1 ; Finish
    "

    if workaround_wine_bug 21939
    then
        try sh "$WINETRICKS" -q wmp9
    fi

    # Should run launcher.exe, but that requires .net and doesn't run on Wine
    # Should give choice of running RE5DX10.EXE, but that requires dx10, which doesn't work on Wine yet
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\CAPCOM\RESIDENT EVIL 5 Benchmark Version"
RE5DX9.EXE
__EOF__
}

#----------------------------------------------------------------

verblist_add quake3         "Quake 3 (ID Software, 1999)" 4d2102a8df3c1fea237f2a6a141346c436614d5e.iso

load_quake3() {
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/4d2102a8df3c1fea237f2a6a141346c436614d5e.iso
    ahk_do "
        Run ${ISO_MOUNT_LETTER}:Setup.exe
        WinWait, Quake III Arena
        ControlClick, x532 y206 ; Click Install
        WinWait, Welcome
        ControlClick, Button1 ; Click Next
        WinWait, Software License Agreement
        ControlClick, Button2 ; Click Yes
        WinWait, Setup Type
        ControlClick, Button2 ; Click Next
        WinWait, Choose Destination Location
        ControlClick, Button1 ; Click Next
        WinWait, Select Program Folder
        ControlClick, Button2 ; Click Next
        WinWait, Question, Would you like to place a Shortcut on your Desktop?
        ControlClick, Button7 ; Click No
        WinWait, Setup Complete
        ControlClick, Button3 ; Click No I will restart my computer later.
        ControlClick, Button5 ; Click Finish
    "
    iso_umount
}

#----------------------------------------------------------------

verblist_add sega_rally_2  "Sega Rally 2 (Sega, 1999)" rally2.exe

# http://appdb.winehq.org/objectManager.php?sClass=application&iId=6961
load_sega_rally_2() {    
    load_autohotkey    
    
    download $PACKAGE http://www2.sega.co.jp/download/pc/rally2/rally2.exe 1c0560c9f7d22343511a8ad46dbe606c6c7417c9
    
    # Installer starts by extracting files, but doesn't seem to be a zip file or a cab file. I tried a few cli arguments,
    # but had no luck. It's only 60 MB extracted, so just extract it fresh each time.
    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, rally2.exe
        winwait, WinSFX32 V2.16.2.6, Install &Directory:
        sleep 1000
        controlclick, Button2, WinSFX32 V2.16.2.6, Install &Directory:
        loop
        {
            ifwinexist, WinSFX32 V2.16.2.6, Install &Directory:
                sleep 5000
            else
                break
        }
    "
    cd rally2/JP_DEMO
    # There's a lot of unknown characters (presumably Japanese). Should this require user to run in
    # a Japanese locale?
    ahk_do "
        SetTitleMatchMode, 2
        run, RALLY2DEMO.EXE
        winwait, ????, SEGA RALLY 2 DEMO ???????
        sleep 1000
        controlclick, Button1, ????, SEGA RALLY 2 DEMO ???????
        winwait, ??????????, ???????????????? SEGA RALLY 2 DEMO ???????????
        sleep 1000
        controlclick, Button1, ??????????, ???????????????? SEGA RALLY 2 DEMO ???????????
        winwait, ??????? ????????, ??????????????????? ????????????? ????????????????????????????????????????????????????[??]???????????????
        sleep 1000
        controlclick, Button2, ??????? ????????, ??????????????????? ????????????? ????????????????????????????????????????????????????[??]???????????????
        winwait, ??????????, SEGA RALLY 2 DEMO
        sleep 1000
        controlclick, Button4, ??????????, SEGA RALLY 2 DEMO
        ; Automatically runs the game after install. Kill it.
        sleep 3000
        process, close, LAUNCH.exe
    "
    cd "$olddir"

    if workaround_wine_bug 22668
    then
        warn "The game is unplayable due to http://bugs.winehq.org/show_bug.cgi?id=22668. No known workaround."
    fi

cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Sega\SEGA RALLY 2 DEMO"
"SEGA RALLY 2 DEMO.exe"
__EOF__

}

#----------------------------------------------------------------

verblist_add 7million      "7Million (Deep Silver, 2009) [download] [broken on wine]" 7Million_0_17_0-full.exe

load_7million() {
    load_autohotkey
    download $PACKAGE http://content.deepsilver.com/kochmedia/downloads/7million/de-uk/7Million_0_17_0-full.exe 99d496817367216180c4b3a59180361c23348e1e

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, 7Million_0_17_0-full.exe
        winwait, Choose Setup Language
        ControlClick, Button1
        SetTitleMatchMode, Slow
        winwait, 7Million - InstallShield Wizard
        sleep 2000
        winactivate, 7Million - InstallShield Wizard
        Send {Enter}
        sleep 4000
        winactivate, 7Million - InstallShield Wizard
        Send !a
        Send !n
        winwait, Age verification
        winactivate, Age verification
        Send !y
        sleep 1000
        winactivate, 7Million - InstallShield Wizard
        Send !i
        winwait, 7Million - InstallShield Wizard, InstallShield Wizard Complete
        Send {Enter}
    "
    cd "$olddir"
    cat > "$DRIVE_C/run-$PACKAGE.bat" << __EOF__
cd "users\\$LOGNAME\Local Settings\Application Data\7Million"
7million
__EOF__
   if workaround_wine_bug 23248
   then
       warn "This game doesn't work on wine yet"
   fi
}

#----------------------------------------------------------------

verblist_add secondlife_beta      "Second Life Viewer - Beta [Download]" Second_Life_2-1-0-207030_Setup.exe

load_secondlife_beta() {
    load_autohotkey
    download $PACKAGE http://download.cloud.secondlife.com/Viewer-2-1/Second_Life_2-1-0-207030_Setup.exe

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, Second_Life_2-1-0-207030_Setup.exe
        winwait, Installer Language
	send {Enter}
        winwait, Installation Folder
	send {Enter}
        winwait, Second Life, Start Second Life now
	send {Tab}{Enter}
    "
    cd "$olddir"

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd $programfilesdir_x86_win\\SecondLifeViewer2
SecondLife.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add sims3         "The Sims 3 (EA, 2009)" 8a82a067f3bb8f68d034a06954e9a16ea381958a.iso

load_sims3() {
    load_autohotkey

    if workaround_wine_bug 22350
    then
        try sh "$WINETRICKS" -q dotnet20
    fi

    if workaround_wine_bug 21517
    then
        try sh "$WINETRICKS" -q d3dx9_36
    fi
    
    # Get user's key
    KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/8a82a067f3bb8f68d034a06954e9a16ea381958a.txt | tr -d -`

    echo KEY is $KEY
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/8a82a067f3bb8f68d034a06954e9a16ea381958a.iso
    # Default lang, USA, accept defaults, uncheck EA dl mgr, uncheck readme
    ahk_do "
        run ${ISO_MOUNT_LETTER}:Sims3Setup.exe
        winwait, Choose Setup Language
        send {Enter}
        SetTitleMatchMode, 2
        winwait, - InstallShield Wizard
        sleep 1000
        ControlClick &Next >, - InstallShield Wizard
        sleep 1000
        send uuuuuu{Tab}{Tab}{Enter}
        sleep 1000
        send a{Enter}
        sleep 1000
        send {Raw}$KEY
        send {Enter}
        winwait, - InstallShield Wizard, Setup Type
        send {Enter}
        winwait, - InstallShield Wizard, Click Install to begin
        send {Enter}
        winwait, - InstallShield Wizard, EA Download Manager
        ControlClick Yes, - InstallShield Wizard
        send {Enter}
        winwait, - InstallShield Wizard, Complete
        ControlClick View the readme file, - InstallShield Wizard
        ControlClick Finish, - InstallShield Wizard
    "
    iso_umount

    cd "$programfilesdir_unix/Electronic Arts/The Sims 3/Game/Bin"
    echo "Sims3 version info:"
    cat skuversion.txt

    download sims3 http://na.llnet.eadownloads.ea.com/u/f/sims/sims3/patches/Sims3_1.6.6.002001_from_1.0.631.00001.exe 02703d296417750005326ff0d37295fa434a3f49

    cd "$WISOTOOL_CACHE"/sims3
    ahk_do "
        run Sims3_1.6.6.002001_from_1.0.631.00001.exe
        SetTitleMatchMode, 2
        winwait, - InstallShield Wizard, Complete
        ControlClick Finish, - InstallShield Wizard
    "

    # FIXME: apply next patch, too

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Electronic Arts\\The Sims 3\\Game\\Bin"
TS3.EXE
__EOF__
}

#----------------------------------------------------------------

verblist_add singularity         "Singularity (Activision, 2010)" cfbba29fa8db1b9f87a90ea2f54c63026757c13d.iso

load_singularity() {
    load_autohotkey

    # Get user's key
    KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/cfbba29fa8db1b9f87a90ea2f54c63026757c13d.txt | tr -d -`

    echo KEY is $KEY
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/cfbba29fa8db1b9f87a90ea2f54c63026757c13d.iso
    ahk_do "
        run ${ISO_MOUNT_LETTER}:setup.exe
        winwait, Activision(R) - InstallShield, Select the language for the installation from the choices below.
        sleep 1000
        controlclick, Button1, Activision(R) - InstallShield, Select the language for the installation from the choices below.
        sleep 1000
        winwait, Singularity(TM), Keycode Check
        sleep 1000
        Send $KEY
        sleep 1000
        Send {Enter}
        ; Well this is annoying...
        Winwait, Keycode Check, The Keycode you entered appears to be valid.
        sleep 1000
        Send {Enter}
        winwait, Singularity(TM), The InstallShield Wizard will install Singularity(TM) on your computer
        sleep 1000
        controlclick, Button1, Singularity(TM), The InstallShield Wizard will install Singularity(TM) on your computer
        winwait, Singularity(TM), Please read the following license agreement carefully
        sleep 1000
        controlclick, Button5, Singularity(TM), Please read the following license agreement carefully
        sleep 1000
        controlclick, Button2, Singularity(TM), Please read the following license agreement carefully
        winwait, Singularity(TM), Minimum System Requirements
        sleep 1000
        controlclick, Button1, Singularity(TM), Minimum System Requirements
        winwait, Singularity(TM), Select the setup type to install
        controlclick, Button4, Singularity(TM), Select the setup type to install
        sleep 5000
        Loop
        {
            ifwinexist, Singularity(TM)
                sleep 15000
            else
                break
        }
        "
    iso_umount

    if workaround_wine_bug 6971
    then
        sh "$WINETRICKS" -q mwo=force
    fi

    if workaround_wine_bug 22548
    then
    echo "Disabling \'depth of field\'"
    cat > "$WISOTOOL_TMP"/dof.reg <<_EOF_
REGEDIT4

[HKEY_CURRENT_USER\Software\Activision\Singularity]
"DepthOfField"=dword:00000000

_EOF_
    try_regedit "$WISOTOOL_TMP_WIN"\\dof.reg
    fi

cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Activision\Singularity(TM)\Binaries"
Singularity.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add splitsecond_demo    "Split Second Demo (Black Rock Studios, 2010) [wine bug 22865]" SplitSecond_Demo.exe

load_splitsecond_demo()
{
    load_autohotkey

    if test ! -f "$WISOTOOL_CACHE/$PACKAGE"/SplitSecond*.exe
    then
        mkdir -p "$WISOTOOL_CACHE/$PACKAGE"
        die "You must download the demo to $WISOTOOL_CACHE/$PACKAGE before running this script.  See http://www.fileplanet.com/212404/210000/fileinfo/Split/Second-Demo"
    fi

    if workaround_wine_bug 22774
    then
        echo "On wine, install takes an extra 7 minutes at the end, please be patient."
    fi

    if workaround_wine_bug 22865
    then
        echo "This game is currently unplayable on wine due to rendering problems; see winehq bug 22865."
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    exe=`ls SplitSecond*.exe`
    ahk_do "
        SetTitleMatchMode, 2
        run, "$exe"
        winwait, Split, Language
        ;ControlClick, Next, Split, Language  ; does not quite work, have to use {Enter} instead
        Send {Enter}
        winwait, Split, game installation
        ControlClick, Button1, Split, game installation
        winwait, Split, license
        ControlClick, Button5, Split, license
        ControlClick, Button2, Split, license
        winwait, Split, DirectX
        ControlClick, Button5, Split, DirectX
        ControlClick, Button2, Split, DirectX
        winwait, Split, installation path
        ControlClick, Button1, Split, installation path
        winwait, Split, Game features
        ControlClick, Button2, Split, Game features
        winwait, Split, start copying
        ControlClick, Button1, Split, start copying 
        winwait, Split, completed
        ControlClick, Button1, Split, completed
        ControlClick, Button4, Split, completed
    "
    cd "$olddir"

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Disney Interactive Studios\\Split Second Demo"
SplitSecondDEMO.exe
__EOF__

}

#----------------------------------------------------------------

verblist_add splitsecond    "Split Second (Black Rock Studios, 2010) [wine bug 22865]" 15548fabe350e1b65432400aae8c3acfb1c930d8.iso

load_splitsecond()
{
    load_autohotkey

    if workaround_wine_bug 22774
    then
        echo "On wine, install takes an extra 7 minutes at the end, please be patient."
    fi

    if workaround_wine_bug 22865
    then
        echo "This game is currently unplayable on wine due to rendering problems; see winehq bug 22865."
    fi

    #KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/15548fabe350e1b65432400aae8c3acfb1c930d8.txt`
    # Key is used in first run activation.  TODO: script first run activation.

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/15548fabe350e1b65432400aae8c3acfb1c930d8.iso

    # Aborts with dialog about FirewallInstallHelper.dll if that's not on the path (e.g. in current dir)
    cd "$ISO_MOUNT_ROOT"
    ahk_do "
        SetTitleMatchMode, 2
        run setup.exe
        winwait, Split, Language
        ;ControlClick, Next, Split, Language  ; does not quite work, have to use {Enter} instead
        Send {Enter}
        winwait, Split, game installation
        ControlClick, Button1, Split, game installation
        winwait, Split, license
        ControlClick, Button5, Split, license
        ControlClick, Button2, Split, license
        winwait, Split, DirectX
        ControlClick, Button5, Split, DirectX
        ControlClick, Button2, Split, DirectX
        winwait, Split, installation method
        send {Enter}
        winwait, DirectX needs to be updated
        send {Enter}
        winwait, Split, begin
        ControlClick, Button1
        winwait, Split, completed
        ControlClick, Button1, Split
        ControlClick, Button4, Split
    "
    iso_umount

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Disney Interactive Studios\\Split Second"
SplitSecond.exe
__EOF__

}

#----------------------------------------------------------------

verblist_add spore    "Spore (EA, 2008)" d08d1985d3161661d4f0ded30a0d11e705f2fcc2.iso

load_spore()
{
    load_autohotkey
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/d08d1985d3161661d4f0ded30a0d11e705f2fcc2.iso
    SPORE_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/d08d1985d3161661d4f0ded30a0d11e705f2fcc2.txt | tr -d -`
    ahk_do "
        SetTitleMatchMode, 2
        run, ${ISO_MOUNT_LETTER}:SPORESetup.exe
        winwait, Language
        controlclick, Button1
        winwait, SPORE, Welcome
        controlclick, Button1
        winwait, SPORE, License
        controlclick, Button3
        controlclick, Button1
        winwait, SPORE, Registration Code
        send {RAW}$SPORE_KEY
        controlclick, Button2
        winwait, SPORE, Setup Type
        controlclick, Button6
        winwait, SPORE, Shortcut
        controlclick, Button6
        winwait, SPORE, begin
        controlclick, Button1
        winwait, Question
        ; download managers are usually a pain, so always say no to such questions
        controlclick, Button2
        winwait, SPORE, complete
        controlclick, Button1
        controlclick, Button2
        controlclick, Button4
    "
    iso_umount
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Electronic Arts\\SPORE\\Sporebin"
SporeApp.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add ssdd2    "SpongeBob SquarePants Diner Dash 2 (Nickelodeon/Big Fish, 2007) [download]" InstallSpongeBobDinerDash2.exe

load_ssdd2()
{
    load_autohotkey
    # Main page: http://arcade.nick.com/nick/gameinfo.jsp?s=SpongeBobDinerDash2
    download $PACKAGE http://nickdownloads.shockwave.com/InstallSpongeBobDinerDash2.exe 8407dae2c062ce62b38408eeac3a9f95be202b96
    
    if workaround_wine_bug 23749
    then
        sh "$WINETRICKS" -q ie6
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run InstallSpongeBobDinerDash2.exe
        winwait, Welcome
        sleep 1000
        controlclick, Button1, Welcome
        sleep 1000
        winwait, End User License
        sleep 1000
        controlclick, Button1, End User License
        winwait, Choose Destination Location
        sleep 1000
        controlclick, Button1, Choose Destination Location
        winwait, FREE Toolbar
        sleep 1000
        controlclick, Button5, FREE Toolbar
        sleep 1000
        controlclick, Button1, FREE Toolbar
        winwait, Start Installation
        sleep 1000
        controlclick, Button1, Start Installation
        winwait, Installation Complete
        sleep 1000
        controlclick, Button1, Installation Complete
    "
    sleep 5
    killall winefile.exe

cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\Nick Arcade\\SpongeBob SquarePants Diner Dash 2"
"SpongeBob SquarePants Diner Dash 2.exe"
__EOF__

}
    
#----------------------------------------------------------------

verblist_add starcraft     "Starcraft Battle Chest (Blizzard, 1998)" 8d6cc11bc76b8af22868a95e17e0282277e9c53c.iso 966bae1f2e2035e066139e78137e623c92838254.iso

load_starcraft() {
    warn "You must have already done 'wisotool load=YOURKEY' on the install disc, and 'wisotool load' on the other disc." 
    load_autohotkey

    # Force clean-ish install
    test -d "$programfilesdir_unix/StarCraft" && rm -rf "$programfilesdir_unix/StarCraft"

    # Get user's key
    KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/8d6cc11bc76b8af22868a95e17e0282277e9c53c.txt`

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/8d6cc11bc76b8af22868a95e17e0282277e9c53c.iso
    ahk_do "
        run ${ISO_MOUNT_LETTER}:StarCraft (Windows).exe
        winwait, StarCraft - Brood War
        send {i}
        winwait, End User License Agreement
        Sleep 2000
        send {a}
        winwait, CD-Key
        send $USERNAME
        send {Tab}$KEY
        send {Enter}
        winwait, Installation Destination Directory
        send {Enter}
        winwait,,Please insert"
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/966bae1f2e2035e066139e78137e623c92838254.iso
    ahk_do "
        send, {Enter}
        SetTitleMatchMode, 2
        winwait, - StarCraft
        winwaitclose, - StarCraft
        Sleep 2000
        send {e}"
    iso_umount

    # FIXME: apply patch, follow instructions in http://us.blizzard.com/support/article.xml?articleId=21150
}

#----------------------------------------------------------------

verblist_add starcraft2    "Starcraft II (Blizzard, 2010)" 044bf7a83b0fc7086a4f89b44ea44d74af320059.iso

# http://appdb.winehq.org/objectManager.php?sClass=version&iId=20882

load_starcraft2() {
    load_autohotkey
    load_gecko

    # Force clean-ish install
    test -d "$programfilesdir_unix/StarCraft II" && rm -rf "$programfilesdir_unix/StarCraft II"

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/044bf7a83b0fc7086a4f89b44ea44d74af320059.iso

    if workaround_wine_bug 23824
    then
        warn "The installer may not run, see http://bugs.winehq.org/show_bug.cgi?id=23824. No known workaround yet."
    fi

    ahk_do "
        SetTitleMatchMode, 2
        run ${ISO_MOUNT_LETTER}:Installer.exe
        winwait, StarCraft II Installer
        ControlClick, x300 y200
        winwait, End User License Agreement
        winactivate
        MouseMove, 300, 300
        Click WheelDown, 70
        Sleep, 1000
        ControlClick, Agree
        winwait, StarCraft II Installer
        sleep 1000
        ControlClick, x800 y500
        winwait, StarCraft II Activation
        sleep 1000
        ; Skip activation
        controlclick, Button2, StarCraft II Activation
        winwait, StarCraft II v, update was successful
        winclose
    "

cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\StarCraft II"
"StarCraft II.exe"
__EOF__
}

#----------------------------------------------------------------
verblist_add sto           "Star Trek Online (Cryptic, 2010)" f891dab46d05d771e0123a1e7ec969f3601064a6.iso

load_sto()
{
    load_autohotkey
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/f891dab46d05d771e0123a1e7ec969f3601064a6.iso
    # Note: http://www.startrekonline.com/download shows how to download the
    # client using bittorrent.  If the iso is not present, we should try that path.

    if workaround_wine_bug 22943
    then
        # Install is fine without ie6, but can't log in or download patch without ie6,
        # and the installer launches the app when it's done.
        # Even with ie6, it's not perfect, there are lots of annoying script error prompts.
        sh "$WINETRICKS" -q ie6
    fi

    ahk_do "
        SetTitleMatchMode, 2
        run ${ISO_MOUNT_LETTER}:setup.exe
        winwait, Installer
        Send {Enter}                        ; Accept English as default language
        winwait, Star Trek Online
        ControlClick, Button2
        winwait, Star Trek, License
        ControlClick, Button2,
        winwait, Star Trek, Location
        ControlClick, Button2
        winwait, Star Trek, shortcuts
        ControlClick, Button2
        winwait, Star Trek, additional
        ControlClick, Button2
        winwait, Star Trek, Launch
        ControlClick, Button2
    " 
    iso_umount
    # FIXME: register using the key that came with the DVD?
    # FIXME: log in and download patch?
    # FIXME: kill game?
}

#----------------------------------------------------------------

verblist_add stfu          "Starwars: The Force Unleashed (Aspyr, 2009)" 0d0f4e826c3a04542a68d7bcc971f4df7526965b.iso 5d6e2eb1b08b9d4a71b2390b385c3048ec91f3df.iso

load_stfu() {
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/0d0f4e826c3a04542a68d7bcc971f4df7526965b.iso
    warn "Starting installer.  This can be very slow, please be patient."
    ahk_do "
        run ${ISO_MOUNT_LETTER}:setup.exe
        SetTitleMatchMode, 2
        winwait, Select Setup Language
        send {Enter}
        winwait, Setup, Welcome
        send {Enter}
        winwait, Setup, License
        sleep 500
        send {Tab}a{Space}{Enter}
        winwait, Setup, Destination
        send {Enter}
        winwait, Setup, Menu
        send {Enter}
        winwait, Setup, Tasks
        send {Space}{Enter}
        winwait, Setup, begin
        sleep 1000
        ControlClick &Install, Setup
        winwait, Setup Needs the Next Disk
    "
    iso_umount
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/5d6e2eb1b08b9d4a71b2390b385c3048ec91f3df.iso
    ahk_do "
        SetTitleMatchMode, 2
        send {Enter}
        winwait, Setup, Completing
        send {Space}{Tab} ; don't show readme
        send {Space}{Tab} ; don't start app
        send {Enter}
    "
    iso_umount

    # Patch to 1.2
    # FIXME: add a commandline option to disable patching in general
    # URL from http://www.lucasfiles.com/index.php?s=&action=download&id=1537&agree=true 
    # See also http://www.forceunleashed.net/news/force-unleashed-patch-1-2/
    download stfu http://xfer.lfnetwork.com/lucasfiles.com/downloads/1537/SWTFU_PC_EF_1.2_Update.exe cfd8043c4b86f4dc0ff0acd4c108b11c4b76e716
    cd "$WISOTOOL_CACHE/stfu"
    ahk_do "
        run SWTFU_PC_EF_1.2_Update.exe
        SetTitleMatchMode, 2
        winwait, Patch
        send {Enter}
        winwait, Patch, Finish
        send {Enter}
    "

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\StarCraft II Beta"
"StarCraft II.exe"
__EOF__

    # Should start SWTFU Launcher.exe, but that doesn't run in Wine?
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Aspyr\Star Wars The Force Unleashed"
SWTFU.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add sf4bench "Street Fighter 4: Benchmark (CAPCOM, 2009) [download]" StreetFighterIV_Benchmark.exe

load_sf4bench()
{
    load_autohotkey

    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/StreetFighterIV_Benchmark.exe"
    then
        download $PACKAGE http://gamedaily.newaol.com/pub/StreetFighterIV_Benchmark.exe f7754210308b3a0ff2bb3be3a62b22767519ca62
    fi

    cd "$WISOTOOL_CACHE"/$PACKAGE

    ahk_do "
        SetTitleMatchmode, 2 
        run, StreetFighterIV_Benchmark.exe
        winwait, Choose
        controlclick, Button1
        winwait, STREET, To continue, click Next
        controlclick, Button1
        winwait, STREET, license agreement
        controlclick, Button3
        controlclick, Button5
        winwait, STREET, Destination Folder
        controlclick, Button1
        winwait, STREET, ready to begin
        controlclick, Button1
        winwait, STREET, successfully installed
        controlclick, Button1

    "

    # The game has a flickering graphics problem when parallel rendering is enabled.
    # You can disable it and tweak benchmark settings via the config.ini file.
    if workaround_wine_bug 23647
    then
        cd "$DRIVE_C/users/$USERNAME/Local Settings/Application Data"
        if test -f CAPCOM/STREETFIGHTERIVBENCHMARK/config.ini
        then
            cd CAPCOM/STREETFIGHTERIVBENCHMARK
            mv config.ini config.ini.old
            sed 's,RenderingThread=ON,RenderingThread=OFF,' config.ini.old > config.ini
        else
            mkdir -p "CAPCOM/STREETFIGHTERIVBENCHMARK"
            cd "CAPCOM/STREETFIGHTERIVBENCHMARK"
            cat > config.ini <<__EOF__
[SYSTEM]
RenderingThread=OFF
[DISPLAY]
Resolution=1024x768
RefreshRate=60Hz
FullScreen=YES
VSync=OFF
FrameRate=VARIABLE
Aspect=AUTO
[GRAPHICS]
MSAA=NONE
TextureFilter=DEFAULT
ModelQuality=HIGH
StageQuality=HIGH
SoftShadowQuality=LOW
SelfShadowQuality=LOW
MotionBlurQuality=LOW
ParticleQuality=MIDDLE
ExtraTouch=OFF
Brightness=50
[BENCHMARK]
Type=BATTLE+DEMO
Loop=OFF
[GAME]
FPS=ON
__EOF__
        fi
    fi

    cd "$olddir"

cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\CAPCOM\\STREETFIGHTERIV_BENCHMARK"
StreetFighterIV_Benchmark.exe
__EOF__
}

verblist_add smbx  "Super Mario Bros. X (Indie, 2009) [download]"  smbx122.exe

load_smbx() {
    load_autohotkey

    # Download URL embedded in http://www.supermariobrothers.org/downloads/smbx122.html
    download $PACKAGE http://www.tehgamez.com/a/smbx122.exe 269eb60d502e57fdfae9c3601ad9ee22801cb5d1

    # This winetricks verb doesn't work on Windows yet, but that's ok-ish, Windows comes with vb6 runtime
    sh "$WINETRICKS" -q vb6run 

    if workaround_wine_bug 23821
    then
        # http://www.supermariobrothers.org/forums/viewtopic.php?f=8&t=6711
	# claims this works
        sh "$WINETRICKS" -q quartz
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"

    ahk_do "
        SetTitleMatchMode, 2
        run smbx122.exe

        WinWait, Setup - Super Mario Bros. X, Welcome
        Send {Enter}
        WinWait, Setup - Super Mario Bros. X, Information
        Send {Enter}
        WinWait, Setup - Super Mario Bros. X, Select Destination Location
        Send {Enter}
        WinWait, Setup - Super Mario Bros. X, Select Start Menu Folder
        Send {Enter}
        WinWait, Setup - Super Mario Bros. X, Additional Tasks
        Send {Enter}
        WinWait, Setup - Super Mario Bros. X, Recommended by
        MouseMove, 36,274
        Click              ; Don't install recommended (Ad) software
        Send {Enter}
        WinWait, Setup - Super Mario Bros. X, Ready to Install
        Send {Enter}
        WinWait, Setup - Super Mario Bros. X, Information
        Send {Enter}
        WinWait, Setup - Super Mario Bros. X, Completing
        Send {Space}   ; Don't run game
        Send {Enter}
    "
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd C:\\SMBX
smbx.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add twfc "Transformers: War for Cybertron (Activision, 2010)" d96a2ebbd15c3d03286d1b8b5601e7038cab46b1.iso

load_twfc() {
    load_autohotkey
    
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/d96a2ebbd15c3d03286d1b8b5601e7038cab46b1.iso
    
    KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/d96a2ebbd15c3d03286d1b8b5601e7038cab46b1.txt | tr -d -`
    
    ahk_do "
    run ${ISO_MOUNT_LETTER}:setup.exe
    SetTitleMatchMode, 2
    winwait, Activision, Select the language for the installation
    sleep 1000
    controlclick, Button1, Activision, Select the language for the installation
    winwait, Transformers, Press NEXT to verify your key
    sleep 1000
    send $KEY
    send {Enter}
    winwait, Keycode Check, The Keycode you entered appears to be valid
    sleep 1000
    send {Enter}
    winwait, Transformers, The InstallShield Wizard will install Transformers
    sleep 1000
    controlclick, Button1, Transformers, The InstallShield Wizard will install Transformers
    winwait, Transformers, License Agreement
    sleep 1000
    controlclick, Button5, Transformers, License Agreement
    sleep 1000
    controlclick, Button2, Transformers, License Agreement
    winwait, Transformers, Minimum System Requirements
    sleep 1000
    controlclick, Button1, Transformers, Minimum System Requirements
    winwait, Transformers, Select the setup type to install
    sleep 1000
    controlclick, Button4, Transformers, Select the setup type to install
    
    ; Installer exits silently. Prevent an early umount:
    sleep 5000
        Loop
        {
            ifwinexist, Transformers
                sleep 15000
            else
                break
        }
    "
    iso_umount

    if workaround_wine_bug 6971
    then
        sh "$WINETRICKS" mwo=force
    fi
    
cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Activision\Transformers - War for Cybertron\Binaries"
TWFC.exe
__EOF__

}

#----------------------------------------------------------------

verblist_add unigine_heaven "Unigen Heaven 2 Benchmark (Unigen, 2010) [download]" Unigine_Heaven-2.0.msi

load_unigine_heaven() {
    load_autohotkey

    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/Unigine_Heaven-2.0.msi"
    then
        warn "This download is slow, you may want to do a manual download from http://downloads.guru3d.com/Unigine-Heaven-DirectX-11-benchmark-2.0-download-2414.html instead"
        #download $PACKAGE http://www.techpowerup.com/downloads/1775e/Unigine_Heaven-2.0.msi 6a0bd499ae8ed8d73d74d964d3c4312a0a40b7e6
        download $PACKAGE http://unigine.com/download/files/Unigine_Heaven-2.0.msi 6a0bd499ae8ed8d73d74d964d3c4312a0a40b7e6
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        run msiexec /i Unigine_Heaven-2.0.msi
        WinWait ahk_class MsiDialogCloseClass 
        Sleep 1000
        Send {Enter}
        WinWait ahk_class MsiDialogCloseClass, License
        ControlClick Button1 ; Accept
        ControlClick Button3 ; Accept
        WinWait ahk_class MsiDialogCloseClass, Choose
        ControlClick Button1 ; Typical
        WinWait ahk_class MsiDialogCloseClass, Ready
        ControlClick Button2 ; Install
        ; FIXME: on systems with OpenAL already (Win7?), the next four lines
        ; are not needed.  We should somehow wait for either OpenAL window
        ; *or* Completed window.
        WinWait ahk_class OpenAL Installer
        ControlClick Button2 ; OK
        WinWait ahk_class #32770
        ControlClick Button1 ; OK

        WinWait ahk_class MsiDialogCloseClass, Completed
        Sleep 500
        ControlClick Button1 ; Finish
        Send {Enter}
    "

    if workaround_wine_bug 22614
    then
        # hope your card actually has 1GB of RAM
        sh "$WINETRICKS" videomemorysize=1024
    fi

    # Should start Heaven.exe, but that doesn't run in Wine
    # Should give option to run Heaven_gl.bat (even works in Wine)
    # or the dx10 or dx11 versions (doesn't).
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Unigine\Heaven"
cmd /c Heaven_d3d9.bat
__EOF__
}

#----------------------------------------------------------------

verblist_add wog           "World of Goo demo (2D Boy, 2008) [download]" WorldOfGooDemo.1.0.exe

load_wog() {
    load_autohotkey

    if ! test -f "$WISOTOOL_CACHE/wog/WorldOfGooDemo.1.0.exe"
    then
        # Get temporary download location
        download wog "http://www.worldofgoo.com/dl2.php?lk=demo&filename=WorldOfGooDemo.1.0.exe"
        URL=`cat "$WISOTOOL_CACHE/wog/dl2.php?lk=demo&filename=WorldOfGooDemo.1.0.exe" | 
           grep WorldOfGooDemo.1.0.exe | sed 's,.*http,http,;s,".*,,'`
        rm "$WISOTOOL_CACHE/wog/dl2.php?lk=demo&filename=WorldOfGooDemo.1.0.exe"
       
        download wog "$URL" e61d8253b9fe0663cb3c69018bb3d2ec6152d488
    fi

    cd "$WISOTOOL_CACHE/wog"
    ahk_do "
        run WorldOfGooDemo.1.0.exe
        winwait, World of Goo Setup, License Agreement
        sleep 1000
        send {Enter}
        winwait, World of Goo Setup, Choose Components
        send {Enter}
        winwait, World of Goo Setup, Choose Install Location
        send {Enter}
        winwait, World of Goo Setup, Thank you
        ControlClick, Make me dirty right now, World of Goo Setup, Thank you
        send {Enter}
        "
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\WorldOfGooDemo"
WorldOfGoo.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add wowtrial       "World of Warcraft trial(Blizzard, 2009)" TryWoW.exe

load_wowtrial() {
    load_autohotkey

    download $PACKAGE https://www.worldofwarcraft.com/downloads/files/pc/enUS/TryWoW.exe 832866b591ea20fa2e5d30c36dcca92aec9ea36a

    ahk_do "
        SetTitleMatchMode, slow
        run "$WISOTOOL_CACHE/$PACKAGE/TryWoW.exe"
        winwait, World of Warcraft Trial v2.0.0.373
        sleep 1000
        controlclick, Button2, World of Warcraft Trial v2.0.0.373
        winwait, World of Warcraft Trial v2.0.0.373, &Agree
        sleep 1000
        controlclick, Static2, World of Warcraft Trial v2.0.0.373
        sleep 1000
        controlclick, Button3, World of Warcraft Trial v2.0.0.373
        winwait, World of Warcraft Trial v2.0.0.373, C:\Program Files\World of Warcraft Trial
        sleep 1000
        controlclick, Button2, World of Warcraft Trial v2.0.0.373, C:\Program Files\World of Warcraft Trial
        ; FIXME: What does the success window look like?
        winwait, Launcher, Launcher requires write permission
        sleep 1000
        controlclick, Button1, Launcher
        "
}

#----------------------------------------------------------------

verblist_add wowbc       "World of Warcraft: Battle Chest (Blizzard, 2008)" \
  c874f5bc676eef8e60d3d232fe6db185c4632fb3.iso

load_wowbc() {
    load_autohotkey
    test -f "$WINDIR"/utorrent.exe || try sh $WINETRICKS utorrent

    case "$LANG" in
    en_US*) ;;
    *) die "This script probably only works for World of Warcraft in the enUS locale."
    esac

    # Torrent file URLs found on http://www.wowwiki.com/Patch_mirrors
    # Patches 3.3.2.11403-to-3.3.3.11685-enUS-patch.exe up to 3.3.5 are downloaded from http://alexsmith.im/wow-patches/enus-patches
    download $PACKAGE "http://a.wirebrain.de/wow/torrent/WoW-3.x.x.x-3.2.0.10192-x86-Win-enUS.torrent" f9e96e7b4edc6a4c22faad084eef147853e3ebb5
    download $PACKAGE "http://a.wirebrain.de/wow/torrent/WoW-3.2.0.10192-3.3.0.10958-x86-Win-enUS.torrent" 33bdf8749b3c3781451b5f6ac2a59ba29d6c61bd
    download $PACKAGE "http://a.wirebrain.de/wow/torrent/WoW-3.3.0.10958-3.3.0.11159-x86-Win-enUS.torrent" b7ad37a75713f6d8e578558ca1e321927192c6c6
    download $PACKAGE "http://a.wirebrain.de/wow/torrent/WoW-3.3.0.11159-to-3.3.2.11403-enUS-patch.torrent" f73763541197fecdcca9b9f8cf91e83cde989a49
    download $PACKAGE "http://uk1.files.alexsmith.im/enUS/WoW-3.3.2.11403-to-3.3.3.11685-enUS-patch.exe" ce73a0a8aa9f6eaf00b5e7cd0a34eb928738fd36
    download $PACKAGE "http://uk1.files.alexsmith.im/enUS/WoW-3.3.3.11685-to-3.3.3.11723-enUS-patch.exe" 
    download $PACKAGE "http://uk1.files.alexsmith.im/enUS/WoW-3.3.3.11723-to-3.3.5.12213-enUS-patch.exe"  

    cd "$WISOTOOL_CACHE/$PACKAGE"
    patch1=`stat -Lc%s WoW-3.2.0-enUS-patch.exe`
    patch2=`stat -Lc%s WoW-3.2.0.10192-to-3.3.0.10958-enUS-patch.exe`
    patch3=`stat -Lc%s WoW-3.3.0.10958-to-3.3.0.11159-enUS-patch.exe`
    patch4=`stat -Lc%s WoW-3.3.0.11159-to-3.3.2.11403-enUS-patch.exe`
    patch5=`stat -Lc%s WoW-3.3.2.11403-to-3.3.3.11685-enUS-patch.exe`
    patch6=`stat -Lc%s WoW-3.3.3.11685-to-3.3.3.11723-enUS-patch.exe`
    patch7=`stat -Lc%s WoW-3.3.3.11723-to-3.3.5.12213-enUS-patch.exe`

    if  [ $patch5 -ne 128600432 ] || [ $patch6 -ne 4959280 ] || [ $patch7 -ne 24886168 ] 
    then
        die "Failed to download patch 3.3.3.11685, or patch 3.3.3.11723, or patch 3.3.5.12213"
    fi

    if [ $patch1 -eq 1323316774 ] && [ $patch2 -eq 572045930 ] && [ $patch3 -eq 5101376 ] && [ $patch4 -eq 167050587 ]
    then
        echo "All patches have been downloaded"
    else
        UT_WINPATH="$WISOTOOL_CACHE_WIN\\wowbc"
        for torrent in `ls *.torrent`
        do
            try $WINE utorrent "/DIRECTORY" "$UT_WINPATH" "$UT_WINPATH\\$torrent" &
        done
    
        # Start uTorrent, have it wait until all downloads are finished
        ahk_do "
            SetTitleMatchMode, 2
            winwait, Torrent
            sleep 3000
            ;App doesnt remember the set as default setting
            winwait, Torrent, default
            send n
            sleep 3000
            ;Cancels bandwidth test on first run of uTorrent
            ifwinactive, Torrent, Bandwidth
            {
              controlclick, Button5, Torrent, Bandwidth
            }
            sleep 1000
            ;Sets paramater to close uTorrent once all downloads are complete
            send !o
            send a{Down}{Enter}
            winwaitclose, Torrent
        "
    fi
    cd "$olddir"

    if ! test -d "$WISOTOOL_TMP"/$PACKAGE/tempcd
    then
        try mkdir -p "$WISOTOOL_TMP"/$PACKAGE/tempcd
        iso_mount "$WISOTOOL_CACHE"/$PACKAGE/c874f5bc676eef8e60d3d232fe6db185c4632fb3.iso
        sleep 5
        try cp -r "$ISO_MOUNT_ROOT"/* "$WISOTOOL_TMP"/$PACKAGE/tempcd
    fi

    # Checks if WoW is installed. If so, skips primary install and proceeds to applying patches
    if ! test -d "$DRIVE_C/Program Files/World of Warcraft"
    then
      ahk_do "
          run "$WISOTOOL_TMP_WIN"/$PACKAGE/tempcd/Installer.exe
          SetTitleMatchMode, 2
          winwait, Burning Crusade Installer
          sleep 4000
          send b
          sleep 2000
          send o
          winwait, License Agreement
          winactivate
          MouseMove, 300, 300
          Click WheelDown, 90
          Sleep, 2000
          ControlClick, Button1
          winwait, Installation Destination Directory
          send {Enter}
          winwait, Manage
          ControlClick, Button2
	  Loop
          {
              ; World Of Warcraft directory is created as .temp, then renamed when done
              ifExist, C:\Program Files\World of Warcraft\Logs\Burning Crusade Install Log.html
                   break
              Sleep 10000
          }
          "
       killall Launcher.exe
       killall Installer.exe
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    for file in \
        WoW-3.2.0-enUS-patch.exe\
        WoW-3.2.0.10192-to-3.3.0.10958-enUS-patch.exe\
        WoW-3.3.0.10958-to-3.3.0.11159-enUS-patch.exe\
        WoW-3.3.0.11159-to-3.3.2.11403-enUS-patch.exe\
        WoW-3.3.2.11403-to-3.3.3.11685-enUS-patch.exe\
        WoW-3.3.3.11685-to-3.3.3.11723-enUS-patch.exe\
        WoW-3.3.3.11723-to-3.3.5.12213-enUS-patch.exe
 

    do
        ahk_do "
           run "$WISOTOOL_CACHE"/$PACKAGE/$file
           SetTitleMatchMode, 2
           winwait, Blizzard Updater
           IfWinExist, Blizzard Updater, unable to start ;Exit if patch is already applied 
           {
             ControlClick, Button1, Blizzard Updater, unable to start
             exit
           }
           else
           {
             winwait, Blizzard Updater, The update was successful
             ControlClick, Button1
             winwait, Launcher
             winkill, Launcher
             winwait, World of Warcraft
             sleep 5000 ; Give time for Play button to appear
             IfWinExist, World of Warcraft, Play ;Exit if last patch is applied
             {
               ; Done!  No more patches.
               winkill, World of Warcraft, Play
             }
             else
             {
               ; Dont let it download the next patch
               winwait, World of Warcraft, Estimated time
               winkill, World of Warcraft, Estimated time
             }
           }
        "
        echo "Patched $file"
        sleep 5
    done
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\World of Warcraft"
Wow.exe
__EOF__
}

#----------------------------------------------------------------

# Generic GOG.com installer
# Usage: game_id game_title [other_files,size [reader_control [run_command [download_id [install_dir [installer_size_and_sha1]]]]]]
# game_id
#     Used for main installer name and download url.
# game_title
#     Used for AutoHotKey and installation path in bat script.
# other_files
#     Extra installer files, in one string, space-separated.
# reader_control
#     If set, the control id of the configuration pannel checkbox controling
#     Adobe Reader installation.
#     Some games don't have it, some games do with different ids.
# run_command
#     Used for bat script, relative to installation path.
# download_id
#     For games which download url doesn't match their game_id
# install_dir
#     If different from game_title
# installer_size_and_sha1
#     exe file SHA1.
_load_gog()
{
    load_autohotkey

    game_id="$1"
    game_title="$2"
    other_files="$3"
    reader_control="$4"
    run_command="$5"
    download_id="$6"
    install_dir="$7"
    installer_size_and_sha1="$8"

    if [ "$download_id"x = ""x ]
    then
        download_id="$game_id"
    fi
    if [ "$install_dir"x = ""x ]
    then
        install_dir="$game_title"
    fi

    installer_path="$WISOTOOL_CACHE/$PACKAGE"
    mkdir -p "$installer_path"
    auth_path="$WISOTOOL_CACHE/gog_auth"
    mkdir -p "$auth_path"
    installer="setup_$game_id.exe"
    cookie="$auth_path/cookie.txt"

    if test "$installer_size_and_sha1"x == ""x
    then
        files="$installer $other_files"
    else
        files="$installer,$installer_size_and_sha1 $other_files"
    fi

    file_id=0
    for file_and_size_and_sha1 in $files
    do
        case "$file_and_size_and_sha1" in
        *,*,*)
            sha1sum=`echo $file_and_size_and_sha1 | sed "s/.*,//"`
            minsize=`echo $file_and_size_and_sha1 | sed 's/[^,]*,\([^,]*\),.*/\1/'`
            file=`echo $file_and_size_and_sha1 | sed 's/,.*//'`
            ;;
        *,*) 
            sha1sum=""
            minsize=`echo $file_and_size_and_sha1 | sed 's/.*,//'`
            file=`echo $file_and_size_and_sha1 | sed 's/,.*//'`
            ;;
        *)
            sha1sum=""
            minsize=1
            file=$file_and_size_and_sha1
            ;;
        esac
        file_path="$installer_path/$file"
        if ! test -s "$file_path" || test `stat -Lc%s "$file_path"` -lt $minsize
        then
            if ! grep "GOGcom_usr" "$cookie" > /dev/null 2>&1
            then
                login_file="$auth_path/login.txt"
                password_file="$auth_path/password.txt"
                if ! test -f "$login_file" -a -f "$password_file"
                then
                    die "Please put your GOG.com login in '$login_file' and password in '$password_file' or put '$file' in '$installer_path'."
                fi
                if ! grep "@" "$login_file" > /dev/null 2>&1
                then
                    die "$login_file must contain your GOG.com login, which is an e-mail address (as opposed to account name)."
                fi
                base_url="https://www.gog.com"
                login_url="/en/login/ajax/"
                next_url="$WISOTOOL_TMP/gog_redir_url"
                post_data="$WISOTOOL_TMP/gog_post_data"
                login="`url_encode < \"$login_file\"`"
                status=$?
                if test $status -ne 0
                then
                     die "Note: login escaping failed with status $status.  Aborting"
                fi
                password="`url_encode < \"$password_file\"`"
                status=$?
                if test $status -ne 0
                then
                     die "Note: password escaping failed with status $status.  Aborting"
                fi
                # Note: just write login & password to a file so they don't appear in "ps"
                echo "a=check&t=old&u=$login&p=$password&r=frontpage" > "$post_data"
                if test -x "`which wget 2>/dev/null`"
                then
                    try wget -O "$next_url" --save-cookies "$cookie" --post-file "$post_data" "$base_url$login_url"
                    try wget -O /dev/null --load-cookies "$cookie" --save-cookies "$cookie" "$base_url`cat \"$next_url\"`"
                else
                    try curl -o "$next_url" --cookie-jar "$cookie" --data "@$post_data" "$base_url$login_url"
                    try curl -o /dev/null --cookie "$cookie" --cookie-jar "$cookie" "$base_url`cat \"$next_url\"`"
                fi
                rm -f "$post_data"
                rm -f "$next_url"
            fi
            nosizecheck=1
            download "$PACKAGE" "https://www.gog.com/en/download/game/$download_id/$file_id" "" "$file" "$cookie"
            unset nosizecheck
            check_sha1=1
            filesize=`stat -Lc%s "$file_path"`
            if test $minsize -gt 1 -a $filesize -ne $minsize
            then
                check_sha1=""
                warn "Expected file size $minsize, please report new size $filesize."
            fi
            if test "$check_sha1" != "" -a "$sha1sum"x != ""x
            then
                verify_sha1sum "$sha1sum" "$file_path"
            fi
        fi
        file_id=`expr $file_id + 1`
    done

    cd "$installer_path"
    ahk_do "
        run $installer
        WinWait, Setup - $game_title, Start installation
        ControlGet, checkbox_state, Checked,, TCheckBox1 ; EULA
        if (checkbox_state != 1) {
            ControlClick, TCheckBox1
        }
        if (\"$reader_control\") {
            ControlClick, TMCoPShadowButton1 ; Options
            Loop, 10
            {
                ControlGet, visible, Visible,, $reader_control
                if (visible)
                {
                    break
                }
                Sleep, 1000
            }
            ControlGet, checkbox_state, Checked,, $reader_control ; Unckeck Adobe/Foxit Reader
            if (checkbox_state != 0) {
                ControlClick, $reader_control
            }
        }
        ControlClick, TMCoPShadowButton2 ; Start Installation
        WinWait, Setup - $game_title, Exit Installer
        ControlClick, TMCoPShadowButton1 ; Exit Installer
        "

    if [ "$run_command"x != ""x ]
    then
        cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__
cd "$programfilesdir_x86_win\\GOG.com\\$install_dir"
$run_command
__EOF__
    fi
}

verblist_add dukenukem3d_gog "Duke Nukem 3D (GOG.com)" setup_duke3d.exe

load_dukenukem3d_gog()
{
    _load_gog "duke3d" "Duke Nukem 3D" "" "TsCheckBox2" "DOSBOX\\dosbox.exe -conf dosboxDuke3D.conf -noconsole -c \"exit\"" "duke_nukem_3d_atomic_edition" "" "28863130,0b86cb60aa2549a46b1bf099a5b544d198ccebaa"
}

verblist_add dukenukemmp_gog "Duke Nukem Manhattan Project (GOG.com)" setup_duke_nukem_manhattan_project.exe

load_dukenukemmp_gog()
{
    _load_gog "duke_nukem_manhattan_project" "Duke Nukem - Manhattan Project" "" "TsCheckBox2" "DukeNukemMP.exe" "" "" "212465575,ffabbc2e96c2c85c4fe8c519afdde2a5226e5ce6"
}

verblist_add ut2004_gog "Unreal Tournament 2004 (GOG.com)" setup_ut2004.exe setup_ut2004-1.bin setup_ut2004-2.bin

load_ut2004_gog()
{
    _load_gog "ut2004" "Unreal Tournament 2004" "setup_ut2004-1.bin,2097510656,77a17856d77545e7930471a3fe3ce210a649edcd setup_ut2004-2.bin,3010009,f327498d0e1f6332d25c18629d277435a6c292da" "TsCheckBox2" "system\\ut2004.exe" "unreal_tournament_2004_ece" "" "2489303,67dfcf2ffa74123436d2cbc010e21d48860ea995"
}

verblist_add abes_oddysee_gog "Abes Oddysee (GOG.com)" AbeWin.exe setup_abes_oddysee.exe

load_abes_oddysee_gog()
{
    _load_gog "abes_oddysee" "Abe's Oddysee" "" "TsCheckBox2" "AbeWin.exe" "oddworld_abes_oddysee" "" "380905004,848b41ac4aaea0e13e5d609bcdc6fe4c9db2368f"
}

verblist_add abes_exoddus_gog "Abes Exoddus (GOG.com)" Exoddus.exe setup_abes_exoddus.exe

load_abes_exoddus_gog()
{
    _load_gog "abes_exoddus" "Abe's Exoddus" "" "TsCheckBox2" "Exoddus.exe" "oddworld_abes_exoddus" "" "625840158,a8f110038c387afa59b0277c2f68dd5e4c27478c"
}

verblist_add beyond_good_and_evil_gog "Beyond Good and Evil (GOG.com)" setup_beyond_good_and_evil.exe

load_beyond_good_and_evil_gog()
{
    _load_gog "beyond_good_and_evil" "Beyond Good and Evil" "" "TsCheckBox2" "gogwrap.exe GOGBEYONDGOODANDEVIL" "" "" "1544566386,cba7c1647c217cfa2db4f770bee35be88b2f08c6"
}

verblist_add far_cry_gog "Far Cry (GOG.com)" setup_far_cry.exe setup_far_cry-1.bin setup_far_cry-2.bin

load_far_cry_gog()
{
    _load_gog "far_cry" "Far Cry" "setup_far_cry-1.bin,2097392384,01819fd08cda4ba5ace4731858e79ef0f5fceca6 setup_far_cry-2.bin,437651497,3796bbd0cb626496fe7cfdd930061821e931fcb5" "TsCheckBox2" "Bin32\\FarCry.exe" "" "" "2607407,0ed9a8976868d2aac1b66a2e216c3d7acac1c3c9"
}

verblist_add descent_1_2_gog "Descent and Descent 2 (GOG.com)" setup_descent_1_2.exe

load_descent_1_2_gog()
{
    # XXX: this installs 2 games, how should bat script be ?
    _load_gog "descent_1_2" "Descent and Descent 2" "" "TsCheckBox5" "" "descent_1_descent_2" "" "577588226,a8f64b537bb3c58aab5955ab92a3e9f6831024fe"
}

verblist_add descent_3_gog "Descent 3 (GOG.com)" setup_descent_3.exe

load_descent_3_gog()
{
    _load_gog "descent_3" "Descent 3 and Mercenary Expansion" "" "TsCheckBox4" "Descent 3.exe" "descent_3_expansion" "Descent 3" "837442501,41342901910aa3d973ef0778cbc9f0d43d5713e9"
}

verblist_add evil_genius_gog "Evil Genius (GOG.com)" setup_evil_genius.exe

load_evil_genius_gog()
{
    _load_gog "evil_genius" "Evil Genius" "" "TsCheckBox2" "ReleaseExe\\EvilGeniusExeStub-Release.exe" "" "" "1394559416,d0bc345e44cd202daa4243315fbb529c042174e0"
}

verblist_add psychonauts_gog "Psychonauts (GOG.com)"  setup_psychonauts.exe

load_psychonauts_gog()
{
    _load_gog "psychonauts" "Psychonauts" "setup_psychonauts-1.bin,2097627392,ba141083b6ac3d82b6e9bf72332d8876c7566378 setup_psychonauts-2.bin,765732413,bef1f8b19c2700e7c81d9aa8a21358266eafe8c9" "TsCheckBox2" "Psychonauts.exe" "" "" "2372340,04f3d2bfb36bb4d7bf5f2800837e218f6a034f4b"
}

verblist_add ut_goty_gog "Unreal Tournament GOTY (GOG.com)" setup_ut_goty.exe

load_ut_goty_gog()
{
    # XXX: Installer window contains: "Unreal Tournament", 2 spaces, a long dash, 1 space "Game Of The Year Edition"
    _load_gog "ut_goty" "Unreal Tournament  " "" "TsCheckBox2" "gogwrap.exe GOGUT" "unreal_tournament_goty" "Unreal Tournament GOTY" "336712863,bd464862181f9a4386e3d10bee616277ecf7e060"
}

verblist_add unreal_gold_gog "Unreal Gold Edition (GOG.com)" setup_unreal_gold.exe

load_unreal_gold_gog()
{
    _load_gog "unreal_gold" "Unreal Gold" "" "TsCheckBox2" "gogwrap.exe GOGUNREAL" "" "" "251958142,189709657792ec89f534b52f31dbe3aba2c6040b"
}

verblist_add unreal_2_se_gog "Unreal 2: The awakening Special Edition (GOG.com)" setup_unreal2_se.exe

load_unreal_2_se_gog()
{
    # \x96 is ansi-1250 for "en dash"
    _load_gog "unreal2_se" "Unreal 2 `echo -e '\x96'` The Awakening Special Edition" "" "TsCheckBox4" "gogwrap.exe GOGUNREAL2" "unreal_2_the_awakening_se" "" "1312187483,0a685f43eb4dcb28e5b8f7f46ff20f05c0082311"
}

verblist_add battle_chess_gog "Battle Chess (GOG.com)" setup_battle_chess.exe

load_battle_chess_gog()
{
    # XXX: this installs 3 games, how should bat script be ?
    _load_gog "battle_chess" "Battle Chess Special Edition" "" "TsCheckBox5" "" "battle_chess_special_edition" "" "46082407,258e74d9a4a2d9d3bd0e261c2a5b229c2b475b9c"
}

verblist_add earth_2150_trilogy_gog "Earth 2150 trilogy (GOG.com)" setup_earth_2150_trilogy.exe

load_earth_2150_trilogy_gog()
{
    # XXX: this installs 3 games, how should bat script be ?
    _load_gog "earth_2150_trilogy" "Earth 2150 Trilogy" "" "TsCheckBox4" "" "" "" "1678391114,898711e463f78182cc008713e0a5be81ead060f0"
}

verblist_add earth_2160_gog "Earth 2160 (GOG.com)" setup_earth_2160.exe

load_earth_2160_gog()
{
    _load_gog "earth_2160" "Earth 2160" "" "TsCheckBox2" "Earth2160_START.exe" "" "" "912927726,5b59076ff5293456ed5043e130bf95e406e1dd73"
}

verblist_add empire_earth_gold_gog "Empire Earth Gold (GOG.com)" setup_empire_earth_gold.exe

load_empire_earth_gold_gog()
{
    # XXX: this installs 2 games, how should bat script be ?
    _load_gog "empire_earth_gold" "Empire Earth Gold Edition" "" "TsCheckBox4" "" "empire_earth_gold_edition" "" "564162686,4fdc33fb072923d36749230df52d28fba3fcefe7"
}

verblist_add earthworm_jim_1_2_gog "Earthworm Jim 1 & 2 (GOG.com)" setup_ewj_1_2.exe

load_earthworm_jim_1_2_gog()
{
    # XXX: this installs 2 games, how should bat script be ?
    _load_gog "ewj_1_2" "Earthworm Jim 1 and 2" "" "TsCheckBox5" "" "earthworm_jim_1_2" "" "622331530,0cf7876691c7fecbe017e7518fd6aab0417ab783"
}

verblist_add shogo_gog "Shogo Mobile Armor Division (GOG.com)" setup_shogo.exe

load_shogo_gog()
{
    # \x96 is ansi-1250 for "en dash"
    _load_gog "shogo" "Shogo `echo -e '\x96'` Mobile Armor Division" "" "TsCheckBox2" "Shogo.exe" "shogo_mobile_armor_division" "" "262247809,9ca006401565a8bf45363c943a4c3cb0b09bec4b"
}

verblist_add settlers_2_gold_gog "The Settlers 2 Gold (GOG.com)" setup_settlers_2_gold.exe

load_settlers_2_gold_gog()
{
    _load_gog "settlers_2_gold" "Settlers 2 GOLD" "" "TsCheckBox2" "DOSBOX\\dosbox.exe -conf dosboxSettlers2.conf -noconsole -c \"exit\"" "the_settlers_2_gold_edition" "" "286716917,efe390e48867edc3840b0d7c9cbab35ea8639b0c"
}

verblist_add robinson_requiem_collection_gog "Robinson Requiem & Deus (GOG.com)" setup_robinson_requiem_collection.exe

load_robinson_requiem_collection_gog()
{
    # XXX: this installs 2 games, how should bat script be ?
    _load_gog "robinson_requiem_collection" "Robinson's Requiem Collection" "" "TsCheckBox5" "" "robinsons_requiem_collection" "" "377524884,d7616bf701da1b48ca4dce4361f96f3d7aefea6d"
}

verblist_add redneck_rampage_gog "Redneck Rampage (GOG.com)" setup_redneck_rampage.exe

load_redneck_rampage_gog()
{
    # XXX: this installs 3 games, how should bat script be ?
    _load_gog "redneck_rampage" "Redneck Rampage Collection" "" "TsCheckbox5" "" "redneck_rampage_collection" "" "636962785,ca1d8c1f276db37b8dc6f93890e09161f990733a"
}

verblist_add praetorians_gog "Praetorians (GOG.com)" setup_praetorians.exe

load_praetorians_gog()
{
    _load_gog "praetorians" "Praetorians" "" "TsCheckBox2" "Praetorians.exe" "" "" "507093445,69da99ab6910550bcb3181df99c8565f99a6c193"
}

verblist_add perimeter_gog "Perimeter (GOG.com)" setup_perimeter.exe

load_perimeter_gog()
{
    _load_gog "perimeter" "Perimeter" "" "TsCheckBox2" "perimeter.exe" "" "" "1340470012,64af926cc8dacda4b9c90efaf16e2e329b5532a7"
}

verblist_add painkiller_black_gog "Painkiller Black (GOG.com)" setup_painkiller_black.exe setup_painkiller_black-1.bin setup_painkiller_black-2.bin

load_painkiller_black_gog()
{
    _load_gog "painkiller_black" "Painkiller Black" "setup_painkiller_black-1.bin,2097647872,f863652603d2a75c746d62c0eddea0a00c7f3fbc setup_painkiller_black-2.bin,1710374334,e1f0e1b648752b8b0ac88c1b715a8a7ba72e85c4" "TsCheckBox2" "bin\\Painkiller.exe" "painkiller" "" "2351728,3648b6b598e2f600fbc711d66a7122c27d7cbbfc"
}

verblist_add operation_flashpoint_goty_gog "Operation Flashpoint GOTY (GOG.com)" setup_operation_flashpoint_goty.exe

load_operation_flashpoint_goty_gog()
{
    # XXX: this installs 2 games, how should bat script be ?
    # \x96 is ansi-1250 for "en dash"
    _load_gog "operation_flashpoint_goty" "Operation Flashpoint `echo -e '\x96'` Game of the Year Edition" "" "TsCheckBox2" "" "" "Operation Flashpoint - GOTY" "769403166,13152a02cc05915f1058b6357c1621aa6c759b62"
}

verblist_add neighbours_from_hell_compilation_gog "Neighbours From Hell 1 & 2 (GOG.com)" setup_neighbours_from_hell_compilation.exe

load_neighbours_from_hell_compilation_gog()
{
    # XXX: this installs 2 games, how should bat script be ?
    _load_gog "neighbours_from_hell_compilation" "Neighbours From Hell Compilation" "" "TsCheckBox4" "" "" "" "373250380,fc7217f7536d0b6fcaef5111b32252bf707f0019"
}

verblist_add mdk_gog "MDK (GOG.com)" setup_mdk.exe

load_mdk_gog()
{
    _load_gog "mdk" "MDK" "" "TsCheckBox4" "gogwrap.exe GOGMDK" "" "" "104786630,0e68fc7a233a8549716d14244f4fc48ef31229e9"
}

verblist_add mdk2_gog "MDK 2 (GOG.com)" setup_mdk_2.exe

load_mdk2_gog()
{
    _load_gog "mdk_2" "MDK 2" "" "TsCheckBox2" "MDK2.exe" "" "" "231939898,e407fc49b06c8332f862b2a952aa62729c7c2388"
}

verblist_add ground_control_2_gog "Ground Control 2 (GOG.com)" setup_ground_control_2.exe

load_ground_control_2_gog()
{
    _load_gog "ground_control_2" "Ground Control II" "" "TsCheckBox2" "gcii.exe" "ground_control_2_operation_exodus" "" "641603732,b2466dd94e5e364e77ba042dc7d33088ffce585f"
}

verblist_add ghost_master_gog "Ghost Master (GOG.com)" setup_ghost_master.exe

load_ghost_master_gog()
{
    _load_gog "ghost_master" "Ghost Master" "" "TsCheckBox2" "ghost.exe" "" "" "537093924,65f89611eaba132c64bac0d1639407419a6628b2"
}

verblist_add freespace_gog "Freespace (GOG.com)" setup_freespace.exe

load_freespace_gog()
{
    _load_gog "freespace" "Freespace with Silent Threat Expansion" "" "TsCheckBox4" "fs.exe" "freespace_expansion" "Freespace" "871259230,99188805dab6b0b67d01b1fb07cf3f6f42334240"
}

verblist_add freespace_2_gog "Freespace 2 (GOG.com)" setup_freespace_2.exe

load_freespace_2_gog()
{
    _load_gog "freespace_2" "Freespace 2" "" "TsCheckBox2" "fs2.exe" "" "" "1669384651,09d2132a413aa76eaab251724ba756409fc0225a"
}

verblist_add flatout_gog "FlatOut (GOG.com)" setup_flatout.exe

load_flatout_gog()
{
    _load_gog "flatout" "FlatOut" "" "TsCheckBox2" "flatout.exe" "" "" "945261967,43e5e28a0a0c9541bbb4f4c664336442903483b3"
}

verblist_add earthworm_jim_3d_gog "Earthworm Jim 3D (GOG.com)" setup_ewj3d.exe

load_earthworm_jim_3d_gog()
{
    _load_gog "ewj3d" "Earthworm Jim 3D" "" "TsCheckBox2" "gogwrap.exe GOGEARTHWORMJIM3D" "earthworm_jim_3d" "" "144186449,3283ce57e845b111afa6df8c315bb57891046678"
}

verblist_add fallout_gog "Fallout (GOG.com)" setup_fallout.exe

load_fallout_gog()
{
    _load_gog "fallout" "Fallout" "" "TsCheckBox2" "falloutw.exe" "" "" "531198473,4c61f9e386dcfd38e55564a0bac26d5a1a8bd52a"
}

verblist_add fallout_2_gog "Fallout 2 (GOG.com)" setup_fallout_2.exe

load_fallout_2_gog()
{
    _load_gog "fallout_2" "Fallout 2" "" "TsCheckBox2" "fallout2.exe" "" "" "609017688,501a8bff61bc03643d32781d0b6b4d9f358fe863"
}

verblist_add fallout_tactics_gog "Fallout Tactics (GOG.com)" setup_fallout_tactics.exe

load_fallout_tactics_gog()
{
    _load_gog "fallout_tactics" "Fallout Tactics" "" "TsCheckBox2" "BOS.exe" "" "" "1629699801,a142ebb287d60e6ba619c8c67ec61270a3313dd3"
}

verblist_add tex_murphy_1_and_2_gog "Tex Murphy 1 & 2 (GOG.com)" setup_tex_murphy_1_and_2.exe

load_tex_murphy_1_and_2_gog()
{
    # XXX: this installs 2 games, how should bat script be ?
    _load_gog "tex_murphy_1_and_2" "Tex Murphy 1 and 2" "" "TsCheckBox5" "" "tex_murphy_1_2" "" "29082356,7aaaa686fdf424fd403bc972cbc94464a2693ce3"
}

verblist_add beneath_a_steel_sky_gog "Beneath a Steel Sky (GOG.com, free)" setup_beneath_a_steel_sky.exe

load_beneath_a_steel_sky_gog()
{
    _load_gog "beneath_a_steel_sky" "Beneath a Steel Sky" "" "TsCheckBox4" "ScummVM\\scummvm.exe -c \"C:\\Program Files\\GOG.com\\Beneath a Steel Sky\\beneath.ini\" beneath" "" "" "75176395,1f99e12643529baa91fecfb206139a8921d9589c"
}

# Brief HOWTO for adding a GOG game:
# - "beneath_a_steel_sky" is the installer exe name, minus "setup_" and ".exe"
# - "Beneath a Steel Sky" is installer window title, minus "Setup - "
# - There are no other files for this game, so this parameter is empty.
#   Otherwise it should be of the following form:
#   file_name[,length[,sha1sum]] [...]
# - "TsCheckBox4" is the control name for the checkbox deciding whether it will
#   install some reader (Foxit in this case, could be acrobat reader). That
#   installation is enabled by default, and would just bloat the generic
#   AutoHotKey script, so it gets disabled.
# - "ScummVM\\[...]" is the command line to run the game, as fetched from the
#   shortcut/launcher installer/wine creates, which will be used in BAT scripts
#   created by wisotool
# - The part in the url which is specific to this game is identical to its "id"
#   (first parameter), so this parameter is left out.
# - The install directory is the same as installer window title (second
#   parameter), so this parameter is left out.
# - Main installer size and sha1sum, separated by a comma.

#----------------------------------------------------------------

# Generic Steam installer
# Usage: app_id game_title game_folder
# app_id
#     Application ID. See http://developer.valvesoftware.com/wiki/Steam_Application_IDs for list.
# game_title
#     Used for AutoHotKey. FIXME: is this guaranteed to match the wiki?
# game_cache_file
#     .gcf or .ncf file name. Note: Does _NOT_ always match the game folder name below.
# game_folder 
#     Folder where files are stored under $STEAMDIR/steamapps/common/
# game_extra_files
#     Most games/demos come with one .gcf or .ncf file, then everything else in the
#     $STEAMDIR/steamapps/common/$game_folder directory. Some (Total War demos) have several 
#     more .gcf/.ncf files. This should be a list, separated by commas.
#
#
# Note: Requires $STEAMUSER $STEAMPASS to be set in your environment or in
# "$WISOTOOL_CACHE"/STEAM_USER" and in "$WISOTOOL_CACHE"/STEAM_PASS"

_load_steam_app()
{
    if [ ! "$STEAM_USER" -a ! -f "$WISOTOOL_CACHE"/STEAM_USER ]
    then
        die "You need to set STEAM_USER variable in your environment or put it in "$WISOTOOL_CACHE"/STEAM_USER"
    elif [ ! "$STEAM_USER" -a -f "$WISOTOOL_CACHE"/STEAM_USER ]
    then
        STEAM_USER=`cat "$WISOTOOL_CACHE"/STEAM_USER`
    fi

    if [ ! "$STEAM_PASS" -a ! -f "$WISOTOOL_CACHE"/STEAM_PASS ]
    then
        die "You need to set STEAM_PASS variable in your environment or put it in "$WISOTOOL_CACHE"/STEAM_PASS"
    elif [ ! "$STEAM_PASS" -a -f "$WISOTOOL_CACHE"/STEAM_PASS ]
    then
        STEAM_PASS=`cat "$WISOTOOL_CACHE"/STEAM_PASS`
    fi

    steam_dir="$programfilesdir_unix/Steam"

    load_autohotkey
    test -f "$steam_dir/Steam.exe" || try sh $WINETRICKS -q steam

    app_id="$1"
    game_title="$2"
    game_cache_file="$3"
    game_folder="$4"
    game_extra_files="$5"
    
    # If files are already cached, skipped downloading/installing and just restore from cache:
    if [ ! -f "$WISOTOOL_CACHE/$PACKAGE/$game_cache_file" ]
    then
        cd "$steam_dir"
        sleep 5
        ahk_do "
        ; Originally used:
        ; run, Steam.exe -login $STEAM_USER $STEAM_PASS -applaunch $app_id
        ; but that doesn't work for all programs. Some would silently fail to start.
        
        ; Instead, run steam in the background, sleep for 30s to give it enough time 
        ; to start, then use the steam:// prototol to install:
        run, Steam.exe -login $STEAM_USER $STEAM_PASS
        ; FIXME: should detect steam running properly...
        ;
        ; Give Steam up to a minute to update itself. Once it is, let it update.
        ; Then give it 30 more seconds.
        ; FIXME: perhaps there's a log/file showing if steam is up to date...
        Winwait, Steam - Updating,,60
        Loop
        {
            SetTitleMatchMode, Slow
            IfWinExist, Steam - Updating
                sleep 10000
            IfWinNotExist, Steam - Updating
                break
        }
        sleep 30000
        run, steam://install/$app_id
        
        ; Info screen, disk space required, etc.
        winwait, Install - $game_title
        winactivate, Install - $game_title
        ; FIXME: How long should this take?
        sleep 10000
        send {enter}
        sleep 10000

        ; Install shortcuts?
        winwait, Install - $game_title
        winactivate, Install - $game_title
        ; FIXME: How long should this take?
        sleep 10000
        send {enter}
        sleep 10000
        
		; Here, it's getting the .gcf/.ncf files. This is normally quick, but can take a long time.
		; Most finish in a few seconds, but the Total War demos takes a couple minutes.
		; So, we'll exit AHK, then wait for all the game files to be present,
        ; before continuing the install.
        exit
		"

        if test ! "$game_extra_files" = ""
        then
            # FIXME: Should we perhaps sha1sum? That would get messy...
            cd steamapps
            IFS=$','
            for x in $game_extra_files
            do
                while true
                do
                    if test -f $x
                    then
                        break
                    else
                        sleep 5
                    fi
                done
            done
            unset IFS
            cd ..
        fi

        # FIXME: Is this a long enough sleep?
        sleep 30
        
        ahk_do "
        winwait, Install - $game_title
        winactivate, Install - $game_title
        ; FIXME: How long should this take?
        sleep 10000
        send {enter}
        "

        # now wait for the download to complete. We're lucky, Steam has some nice logging
        # so we wait until Steam reports the download is complete. Then, to be safe, sleep
        # and extra 30 seconds, shutdown steam nicely, and finally, cache everything.
        # These are the lines I found for success:
        #
        # $steam_dir/logs/download_log.txt
        # [2010-06-17 00:53:06]: Got eSteamNotifyAppDownloadingPaused for AppID 6110
        # [2010-06-17 00:53:06]: AppID 6110 is now marked not downloading
        # [2010-06-17 00:53:06]: Got eSteamNotifyCacheLoadingCompleted for AppID 6110
        # [2010-06-17 00:53:06]: SetHasAllLocalContent(true) called for 6110
        # FIXME: are any of these safe to use?

        dl_log="$steam_dir/logs/download_log.txt"
        while true
        do
            grep "SetHasAllLocalContent(true) called for $app_id" "$dl_log" && break
            sleep 15
        done

        sleep 30
        $WINE Steam.exe -shutdown
        mkdir -p "$WISOTOOL_CACHE/$PACKAGE"
        cp -r "$steam_dir/steamapps/common/$game_folder" "$WISOTOOL_CACHE/$PACKAGE"
        cp -r "$steam_dir/steamapps/$game_cache_file" "$WISOTOOL_CACHE/$PACKAGE"
        if test ! "$game_extra_files" = ""
        then
            IFS=$','
            for x in $game_extra_files
            do
                cp "$steam_dir/steamapps/$x" "$WISOTOOL_CACHE/$PACKAGE"
            done
            unset IFS
        fi
    else
        mkdir -p "$steam_dir/steamapps/common"
        cp -r "$WISOTOOL_CACHE/$PACKAGE/$game_folder" "$steam_dir/steamapps/common"
        cp -r "$WISOTOOL_CACHE/$PACKAGE/$game_cache_file" "$steam_dir/steamapps" 
        if test ! "$game_extra_files" = ""
        then
            IFS=$','
            for x in $game_extra_files
            do
                cp "$WISOTOOL_CACHE/$PACKAGE/$x" "$steam_dir/steamapps"
            done
            unset IFS
        fi
    fi

    
cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Steam"
.\Steam.exe -login $STEAM_USER $STEAM_PASS -applaunch $app_id
__EOF__

}

# Sorted by app_id:

verblist_add multiwinia_demo_steam "Multiwinia: Demo (Steam, 2008)" "multiwinia content.ncf"

load_multiwinia_demo_steam()
{
    _load_steam_app "1540" "Multiwinia Demo" "multiwinia content.ncf" "multiwinia"
}

verblist_add arx_fatalis_demo_steam "Arx Fatalis Demo (Steam, 2008)" "arx fatalis base.ncf"

load_arx_fatalis_demo_steam()
{
    _load_steam_app "1710" "Arx Fatalis" "arx fatalis base.ncf" "arx fatalis"
}

verblist_add painkiller_demo_steam "Painkiller Demo (Steam, 2004)" "painkiller demo content.ncf"

load_painkiller_demo_steam()
{
    _load_steam_app "3210" "Painkiller Demo" "painkiller demo content.ncf" "painkiller demo"
}

verblist_add bookworm_adventures_deluxe_demo_steam "Bookworm Adventures Deluxe Demo (Steam, 2007)" "bookworm adventures deluxe content.ncf"

load_bookworm_adventures_deluxe_demo_steam()
{
    _load_steam_app "3270" "Bookworm Adventures Deluxe Demo" "bookworm adventures deluxe content.ncf" "bookworm adventures deluxe"
}

verblist_add zen_of_sudoku_demo_steam "Zen of Sudoku Demo (Steam, 2006)" "zenofsudoku.ncf"

load_zen_of_sudoku_demo_steam()
{
    _load_steam_app "4910" "Zen of Sudoku Demo" "zenofsudoku.ncf" "zen of sudoku"
}

verblist_add eets_demo_steam "Eets Demo (Steam, 2006)" "eets content.ncf"

load_eets_demo_steam()
{
    _load_steam_app "6110" "Eets Demo" "eets content.ncf" "eets"
}

verblist_add longest_journey_demo_steam "The Longest Journey Demo (Steam, 2000)" "the longest journey demo content.ncf"

load_longest_journey_demo_steam()
{
    _load_steam_app "6320" "The Longest Journey Demo" "the longest journey demo content.ncf" "the longest journey demo"
}

verblist_add joint_task_force_demo_steam "Joint Task Force Demo (Steam, 2006)" "joint task force demo content.ncf"

load_joint_task_force_demo_steam()
{
    _load_steam_app "6410" "Joint Task Force Demo" "joint task force demo content.ncf" "joint task force demo"
}

verblist_add lost_planet_dx9_demo_steam "Lost Planet Extreme Condition Demo (Steam, 2007)" "lost planet demo dx9 content.ncf"

load_lost_planet_dx9_demo_steam()
{
    _load_steam_app "6530" "Lost Planet Extreme Condition Demo" "lost planet demo dx9 content.ncf" "lost planet demo"
}

verblist_add lost_planet_dx10_demo_steam "Lost Planet Extreme Condition DX10 Demo (Steam, 2007)" "lost planet demo dx10 content.ncf"

load_lost_planet_dx10_demo_steam()
{
    _load_steam_app "6540" "Lost Planet Extreme Condition DX10 Demo" "lost planet demo dx10 content.ncf" "lost planet dx10 demo"
}

verblist_add total_war_and_empire_demo_steam "Empire: Total War Demo (Steam, 2009)" "empire total war demo main.ncf"

load_total_war_and_empire_demo_steam()
{
    _load_steam_app "10620" "Empire: Total War" "empire total war demo main.ncf" "empire total war demo" "empire total war demo english.ncf,empire total war demo executable.ncf,empire total war demo redist.ncf"

    if workaround_wine_bug 18490
    then
        warn "You'll probably want the patch from http://bugs.winehq.org/show_bug.cgi?id=18490. Otherwise, the game will crash when starting a battle."
    fi

}

verblist_add napoleon_total_war_demo_steam "Napoleon: Total War Demo (Steam, 2010)" "napoleon total war demo english.ncf"

load_napoleon_total_war_demo_steam()
{
    _load_steam_app "34050" "Napoleon: Total War" "napoleon total war demo english.ncf" "napoleon total war demo" "napoleon total war demo data_34052.ncf,napoleon total war demo exe_34051.ncf,napoleon total war demo redist_34053.ncf"

    if workaround_wine_bug 23126
    then
        try sh "$WINETRICKS" -q vcrun2005
    fi

    if workaround_wine_bug 23356
    then
        try sh "$WINETRICKS" -q d3dx9
    fi

    if workaround_wine_bug 18490
    then
        warn "You'll probably want the patch from http://bugs.winehq.org/show_bug.cgi?id=18490. Otherwise, the game will crash when starting a battle."
    fi

}

#----------------------------------------------------------------

print_version() {
    echo "$VERSION"
}

#--------- Main program -----------------------------------------

olddir=`pwd`
srcdir=`dirname $0`
srcdir=`cd $srcdir; /bin/pwd`

# Load external verbs.  Filenames may not contain spaces.
if cd "$WISOTOOL_VERBS"
then
    for file in `find . -type f -name '*.verb' 2>/dev/null` 
    do
       . $file
    done
fi
cd "$olddir"

verblist_finish

# On Solaris, choose more modern commands (needed for id -u).
case `uname -s` in
SunOS) PATH="/usr/xpg6/bin:/usr/xpg4/bin:$PATH"
      ;;
esac

case "$1" in
-V|--version)
    echo "wisotool version $VERSION.  (C) 2007-2010 Dan Kegel et al.  LGPL."
    exit 0
    ;;
esac

detect_menu
detect_sudo

GUI=0
case x"$1" in
x) GUI=1 ;;
x-h|x--help|xhelp) usage ; exit 1 ;;
esac

case "$OS" in
 "Windows_NT")
  ;;
 *)
  # Prevent running with wrong user id.
  # It's bad to create files as the wrong user!
  die_if_user_not_dirowner "$WINEPREFIX"
  # Wine misbehaves strangely if user doesn't own the parent of $WINEPREFIX.
  die_if_user_not_dirowner "$WINEPREFIX/.."

  if [ ! -x "`which "$WINE" 2>/dev/null`" ]
  then
      die "Cannot find wine ($WINE)"
  fi

  # Create wineprefix if not already there
  test -d "$WINEPREFIX" || WINEDLLOVERRIDES=mshtml= $WINE cmd /c echo yes > /dev/null 2>&1
  ;;
esac

mkdir -p "$WISOTOOL_TMP"

case $GUI in
1) showmenu ; set $todo ;;
esac

mkdir -p "$WISOTOOL_CACHE"

WINETRICKS="$srcdir/winetricks"
if ! test -f "$WINETRICKS"
then
    WINETRICKS="$WISOTOOL_CACHE/winetricks"
    download . http://kegel.com/wine/winetricks
fi

# The folder-name is localized!
programfilesdir_win="`unset WINEDEBUG; WINEDLLOVERRIDES=mshtml= $WINE cmd.exe /c echo "%ProgramFiles%" | tr -d '\015'`"
test x"$programfilesdir_win" != x || die "$WINE cmd.exe /c echo '%ProgramFiles%' returned empty string"
case "$programfilesdir_win" in
%*) die "$WINE cmd.exe /c echo '%ProgramFiles%' returned unexpanded string... do you own the parent of $WINEPREFIX ?"
esac
programfilesdir_unix="`unset WINEDEBUG; $XXXPATH -u "$programfilesdir_win" | tr -d '\015' `"
test x"$programfilesdir_unix" != x || die "winepath -u $programfilesdir_win returned empty string"
wisotool_tmp_win="`$XXXPATH -w "$WISOTOOL_TMP"`"

# 64 bit windows has a second directory for program files
programfilesdir_x86_win="${programfilesdir_win} (x86)"
programfilesdir_x86_unix="${programfilesdir_unix} (x86)"
if ! test -d "$programfilesdir_x86_unix"
then
    programfilesdir_x86_win="${programfilesdir_win}"
    programfilesdir_x86_unix="${programfilesdir_unix}"
fi
export programfilesdir_x86_unix

# (Fixme: get fonts path from SHGetFolderPath
# See also http://blogs.msdn.com/oldnewthing/archive/2003/11/03/55532.aspx)
#
# Did the user rename Fonts to fonts?
if test ! -d "$WINDIR"/Fonts && test -d "$WINDIR"/fonts
then
    winefontsdir="$WINDIR"/fonts
else
    winefontsdir="$WINDIR"/Fonts
fi

# Mac folks tend to not have sha1sum, but we can make do with openssl
if [ -x "`which sha1sum 2>/dev/null`" ]
then
   SHA1SUM="sha1sum"
elif [ -x "`which openssl 2>/dev/null`" ]
then
   SHA1SUM="openssl dgst -sha1"
else
   die "No sha1sum utility available."
fi

if [ ! -x "`which unzip 2>/dev/null`" ]
then
    die "Cannot find unzip.  Please install it (e.g. 'sudo apt-get install unzip' or 'sudo yum install unzip')."
fi

while test "$1" != ""
do
    PACKAGE=$1
    # Kludge: shorthand synonyms.  Find some more elegant way of doing this.
    case $PACKAGE in
    dao) PACKAGE=dragonage ;;
    sc2) PACKAGE=starcraft2 ;;
    esac

    case $PACKAGE in
    -q) WISOTOOL_QUIET="/q"
        WINEDEBUG=${WINEDEBUG:-"fixme-all"}
        export WINEDEBUG
        ;;
    -v) set -x;;
    ls) list_available_verbs;;
    load) load_iso dd;;
    load_harder) load_iso ddrescue;;
    load=*) key="`echo $PACKAGE | sed 's/load=//'`"; load_iso dd "$key";;
    migrate) migrate_files;;
    version) print_version;;

    *.verb)
       case $1 in
       */*) . $1 ;;
       *) . ./$1 ;;
       esac
       PACKAGE=`echo $1 | sed 's,.*/,,;s,.verb,,'`
       load_$PACKAGE
       ;;
    *) if verblist_is_legal_verb $PACKAGE
       then
           load_$PACKAGE
       else
           echo Unknown arg $PACKAGE; usage ; exit 1;
       fi
       ;;
    esac
    # Provide a bit of feedback
    test "$WISOTOOL_QUIET" = "" && case $PACKAGE in
    -q) echo Setting quiet mode;;
    -v) echo Setting verbose mode;;
    *) #echo "$PACKAGE done" ;;
    esac
    shift

    # User-specific postinstall hook.  
    # Source it so the script can call download() if needed.
    if [ -f "$WISOTOOL_POST"/$PACKAGE/$PACKAGE-postinstall.sh ]
    then
        chmod +x "$WISOTOOL_POST/$PACKAGE/$PACKAGE-postinstall.sh"
        ( . "$WISOTOOL_POST"/$PACKAGE/$PACKAGE-postinstall.sh )
    fi
done

test "$WISOTOOL_CACHE_SYMLINK" && rm -f "$WISOTOOL_CACHE_SYMLINK"

# remove the temp directory
chmod -R 700 "$WISOTOOL_TMP"
rm -rf "$WISOTOOL_TMP"
openSUSE Build Service is sponsored by