#!/bin/sh
# Quick and dirty script to download and install various apps user #1 needs
#
# Copyright 2007, 2008 Google (Dan Kegel, dank@kegel.com)
# Borrowed liberally from winetricks

# Default values for important settings if not already in environment.
# These settings should not need editing here.
WINE=${WINE:-wine}
WINEPREFIXCREATE=${WINEPREFIXCREATE:-wineprefixcreate}
WINEPREFIX=${WINEPREFIX:-$HOME/.wine}

# Internal variables; these locations are not too important
WINETRICKS_CACHE=$HOME/winetrickscache
# Default to hiding the directory, by popular demand
test -d "$WINETRICKS_CACHE" || WINETRICKS_CACHE=$HOME/.winetrickscache
WINETRICKS_TMP="$WINEPREFIX"/drive_c/winetrickstmp
mkdir -p "$WINETRICKS_TMP"
WINETRICKS_TMP_WIN='c:\winetrickstmp'

# Which sourceforge mirror to use.  Rotate based on time, since 
# their mirror picker sometimes persistantly sends you to a broken
# mirror.
case `date +%S` in
*[01]) SOURCEFORGE=http://internap.dl.sourceforge.net/sourceforge ;;
*[23]) SOURCEFORGE=http://easynews.dl.sourceforge.net/sourceforge ;;
*)     SOURCEFORGE=http://downloads.sourceforge.net;;
esac

die() {
  echo "$@"

  case x"$GUI" in
  x1) xmessage -center "               Winetricks error: $@                 " ;;
  *) ;;
  esac

  exit 1
}

which "$WINE" > /dev/null
if test "$?" -ne "0"
then
  die "Cannot find wine ($WINE)"
fi

which "$WINEPREFIXCREATE" > /dev/null
if test "$?" -ne "0"
then
  die "Cannot find wineprefixcreate ($WINEPREFIXCREATE)"
fi

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

usage() {
    set +x
    echo "Usage: $0 [options] package [package] ..."
    echo "This script can help you prepare your system for Windows applications"
    echo "that mistakenly assume all users' systems have all the needed"
    echo "redistributable runtime libraries or fonts."
    echo "Some options require the Linux 'cabextract' program."
    echo ""
    echo "Options:"
    echo " -q         quiet.  You must have already agreed to the EULAs."
    echo " -v         verbose"
    echo "Packages:"    
    echo " dbpoweramp"
    echo " dvdshrink"
    echo " flickr_uploader"
    echo " font_xplorer"
    echo " mahjongg"
    echo " mmexporter"
    echo " musicmatch9"
    echo " mp3recorder"
    echo " powerstructure"
    echo " roughdraft"
    echo " shisensho"
    echo " sony_dve"
    echo " tivo_desktop"
    echo " topstyle_lite"
    echo " all        install them all"
}

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

# Checks for known desktop environments
# set variable DE to the desktop environments name, lowercase

detectDE() {
    if [ x"$KDE_FULL_SESSION" = x"true" ]
    then 
        DE=kde
    elif [ x"$GNOME_DESKTOP_SESSION_ID" != x"" ]
    then
        DE=gnome
    elif [ x"$DISPLAY" != x"" ]
    then
        DE=x
    else 
        DE=none
    fi
}

kde_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
}

x_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") > /tmp/x_showmenu.txt 
    xmessage -print -file /tmp/x_showmenu.txt -buttons "Cancel,$args" | sed 's/Cancel//'
}

showmenu()
{
    detectDE
    case $DE in
    kde) kde_showmenu "$@" ;;
    #gnome) gnome_showmenu "$@" ;;
    x) x_showmenu "$@" ;;
    none) usage 1>&2; exit 1;;
    esac
}
 
dogui()
{
  detectDE
  if [ $DE = gnome ]
  then
    echo "zenity --title 'Select a package to install' --text 'Install?' --list --checklist --column '' --column Package --column Description --height 400 --width 400 \\" > $WINETRICKS_TMP/zenity.sh
    usage | grep '^ [a-z]' | sed 's/^ \([^ ]*\) *\(.*\)/FALSE "\1" '"'\2'/" | sed 's/$/ \\/' >> $WINETRICKS_TMP/zenity.sh
    export todo="`sh $WINETRICKS_TMP/zenity.sh | tr '|' ' '`"
  else
    packages=`usage | awk '/^ [a-z]/ {print $1}'`
    export todo="`showmenu "migrating-user-1" "Select a package to install" "Install?" "Package" $packages`"
  fi

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

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

GUI=0
case x"$1" in
x) GUI=1; dogui ; set $todo ;;
x-h|x--help|xhelp) usage ; exit 1 ;;
esac
test -d "$WINEPREFIX" || $WINEPREFIXCREATE > /dev/null 2>&1
mkdir -p "$WINETRICKS_CACHE"
olddir=`pwd`
# Clean up after failed runs, if needed
rm -rf "$WINETRICKS_TMP"/*

# The folder-name is localized!
programfilesdir_win=`$WINE cmd.exe /c echo "%ProgramFiles%"`
programfilesdir_unix=`$WINE winepath -u "$programfilesdir_win"`

# Did the user rename Fonts to fonts?
if ! test -d "$WINEPREFIX"/drive_c/windows/Fonts && test -d "$WINEPREFIX"/drive_c/windows/fonts 
then
    winefontsdir="$WINEPREFIX"/drive_c/windows/fonts
else
    winefontsdir="$WINEPREFIX"/drive_c/windows/Fonts
fi

# Mac folks tend to not have sha1sum, but we can make do with openssl
if [ -x "`which sha1sum`" ]
then
   SHA1SUM="sha1sum"
else
   SHA1SUM="openssl dgst -sha1"
fi

which cabextract > /dev/null
if test "$?" -ne "0"
then
  echo "Cannot find cabextract.  Please install it (e.g. 'sudo apt-get install cabextract' or 'sudo yum install cabextract')."
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 "$@"
    "$@"
    status=$?
    if test $status -ne 0
    then
        die "Note: command '$@' returned status $status.  Aborting."
    fi
}

# 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
}

# Download a file
# Usage: package url [sha1sum [filename]]
# Caches downloads in winetrickscache/$package
download() {
    if [ "$4"x != ""x ]
    then
        file="$4"
    else
        file=`basename "$2"`
    fi
    cache="$WINETRICKS_CACHE/$1"
    mkdir -p "$cache"
    if ! 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!
        if [ -x "`which wget`" ]
        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)
           try wget -nd -c --read-timeout=300 --retry-connrefused --header "Accept-Encoding: gzip,deflate" "$2"
        else
           # curl doesn't get filename from the location given by the server!
           # fortunately, we know it
           try curl -L -o $file -C - --header "Accept-Encoding: gzip,deflate" "$2"
        fi
        cd $olddir
    fi
    if [ "$3"x != ""x ]
    then
	verify_sha1sum $3  "$cache/$file"
    fi
}

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

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

_EOF_
    try $WINE regedit "$WINETRICKS_TMP"/set-winver.reg
}

unset_winver() {
    echo "Clearing Windows version back to default"
    cat > "$WINETRICKS_TMP"/unset-winver.reg <<_EOF_
REGEDIT4

[HKEY_CURRENT_USER\Software\Wine]
"Version"=-

_EOF_
    try $WINE regedit "$WINETRICKS_TMP"/unset-winver.reg
}

override_dlls() {
    mode=$1
    shift
    echo Using $mode override for following DLLs: $@
    cat > "$WINETRICKS_TMP"/override-dll.reg <<_EOF_
REGEDIT4

[HKEY_CURRENT_USER\Software\Wine\DllOverrides]
_EOF_
    while test "$1" != ""
    do
        case "$1" in
        comctl32)
           rm -rf "$WINEPREFIX"/drive_c/windows/winsxs/manifests/x86_microsoft.windows.common-controls_6595b64144ccf1df_6.0.2600.2982_none_deadbeef.manifest
           ;;
        esac
        echo "\"$1\"=\"$mode\"" >> "$WINETRICKS_TMP"/override-dll.reg
	shift
    done

    try $WINE regedit "$WINETRICKS_TMP"/override-dll.reg
    rm "$WINETRICKS_TMP"/override-dll.reg
}

override_app_dlls() {
    app=$1
    shift
    mode=$1
    shift
    echo Using $mode override for following DLLs when running $app: $@
    ( 
    echo REGEDIT4 
    echo "" 
    echo "[HKEY_CURRENT_USER\\Software\\Wine\\AppDefaults\\$app\\DllOverrides]" 
    ) > "$WINETRICKS_TMP"/override-dll.reg 

    while test "$1" != ""
    do
        case "$1" in
        comctl32)
           rm -rf "$WINEPREFIX"/drive_c/windows/winsxs/manifests/x86_microsoft.windows.common-controls_6595b64144ccf1df_6.0.2600.2982_none_deadbeef.manifest
           ;;
        esac
        echo "\"$1\"=\"$mode\"" >> "$WINETRICKS_TMP"/override-dll.reg
	shift
    done

    try $WINE regedit "$WINETRICKS_TMP"/override-dll.reg
    rm "$WINETRICKS_TMP"/override-dll.reg
}

register_font() {
    file=$1
    shift
    font=$1
    #echo "Registering $file as $font"
    cat > "$WINETRICKS_TMP"/register-font.reg <<_EOF_
REGEDIT4

[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Fonts]
"$font"="$file"
_EOF_
    # too verbose
    #try $WINE regedit "$WINETRICKS_TMP"/register-font.reg
    $WINE regedit "$WINETRICKS_TMP"/register-font.reg
}

#----- One function per package, in alphabetical order ----------

load_audiolib_mp3_recorder() {
    download . http://www.audiolib.com/recorder/alrecorder.exe adc1b944eff44ce10f9dc03c5cd6dadade11bb78
    try $WINE "$WINETRICKS_CACHE"/alrecorder.exe $WINETRICKS_SILENT_INNO
}

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

load_dvdshrink() {
    download dvdshrink "http://www.afterdawn.com/software/dawnload.cfm?mirror_id=0&version_id=1421&software_id=519" 011c6a1caa485c54b585d774d6438473ce5f9b39 dvdshrink32setup1.zip
    cd "$WINETRICKS_CACHE"/dvdshrink
    test -f dvdshrink32setup.exe || try unzip dvdshrink32setup1.zip dvdshrink32setup.exe
    try $WINE dvdshrink32setup.exe $WINETRICKS_SILENT_INNO
    cd "$olddir"
}

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

load_newsgator_topstyle_lite() {
    download . http://www.newsgator.com/download/products/ts3lite.exe 45e1e0953587a0150b8121200fd1e0f50f8f817a
    try $WINE "$WINETRICKS_CACHE"/ts3lite.exe $WINETRICKS_S
}

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

load_joerg_mm_exporter() {
    download . "http://mm-exporter.joexx.de/dl_manager/get_dl_mm_en.php?action=download&id=1" a36f008c07075317572c16c1870e993986192e1f  MM-Exporter_233_Setup.exe

    try $WINE "$WINETRICKS_CACHE"/MM-Exporter_233_Setup.exe $WINETRICKS_SILENT_INNO
}

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

load_valot_shisen_sho() {
    download . http://dvalot.free.fr/download/SHISENST.EXE 2615885a85c4009a60182814138784a9073fa64e

    try $WINE "$WINETRICKS_CACHE"/SHISENST.EXE $WINETRICKS_S
}

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

load_valot_mah_jongg() {
    download . http://dvalot.free.fr/download/MAHINST.EXE 9b3c7ec1dfaf838736b85ebe8dc0a0e9e90e4876

    try $WINE "$WINETRICKS_CACHE"/MAHINST.EXE $WINETRICKS_S
}

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

load_dbpoweramp() {
    download . http://www.dbpoweramp.com/bin/dMC-r12.4.exe c8e03aaa60bfb61fadb7c83652f362cd0ea04d99  

    try $WINE "$WINETRICKS_CACHE"/dMC-r12.4.exe $WINETRICKS_SILENT_SPOON
}

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

load_font_xplorer() {
    download . "http://www.moonsoftware.com/getfile.asp?fxfull" 22feb63be28730cbfad5458b139464490a25a68d  Font_Xplorer_122_Free.exe  

    try $WINE "$WINETRICKS_CACHE"/Font_Xplorer_122_Free.exe $WINETRICKS_S
}

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

load_musicmatch9() {
    download . http://download.oldversion.com/mmatch90.exe eff87a6e972c07649af8be8269a6ca82a08d6b3f

    try $WINE "$WINETRICKS_CACHE"/mmatch90.exe
}

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

load_pixie() {
    download pixie http://www.nattyware.com/bin/pixie.zip 608ab6b47b3e4e23160738cbf4f05fdeffcb42c5

    cd "$WINETRICKS_CACHE"/pixie
    test -f pixie.exe  || try unzip pixie.zip 
    try $WINE pixiesetup.exe $WINETRICKS_S
    cd "$olddir"
}

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

load_powerstructure() {
    download . http://www.write-brain.com/power_structure/power-structure-demo.exe 9dbc0f143ee16e2e80f1685bb8bd34445c159420

    try $WINE "$WINETRICKS_CACHE"/power-structure-demo.exe
}

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

load_roughdraft() {
    download . http://www.salsbury.f2s.com/roughdraft/RDraft30.exe 4071949b7497fbd136a142a28e4551501c8e8ef1

    try $WINE "$WINETRICKS_CACHE"/RDraft30.exe $WINETRICKS_S
}

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

load_sony_dve() {
    download . ftp://download.sony.com/US/voicerecorder/DVESETUP_EN.EXE 09f94dda1dc413f18cba22d3785fc262b421b1ec

    # silent would be /S /A /S, but it hangs at end, so don't bother
    try $WINE "$WINETRICKS_CACHE"/DVESETUP_EN.EXE 
}

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

load_tivo_desktop() {
    download . http://www.tivo.com/assets/exe/tivotogo/TiVoDesktop2.6.1.exe c6e95ba0231125b107d44fe0eb8d8c452bdda614

    try $WINE "$WINETRICKS_CACHE"/TiVoDesktop2.6.1.exe $WINETRICKS_S
}

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

load_flickr_uploader() {
    download . http://h.yimg.com/ce/flickr/uploadr_2.5.0.15_en.exe afc0fe65a9e080be3710f2d7a26672359ea2eaeb

    try $WINE "$WINETRICKS_CACHE"/uploadr_2.5.0.15_en.exe  $WINETRICKS_S
}


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

while test "$1" != ""
do
    PACKAGE=$1
    case $1 in
    -q) WINETRICKS_QUIET="/q"
        WINETRICKS_UNIXQUIET="-q"
        WINETRICKS_SILENT="/silent"
        WINETRICKS_SILENT_SPOON="--silent"
        WINETRICKS_S="/S"                 # for NSIS installers
        WINETRICKS_SILENT_INNO="/sp- /silent"
        WINEDEBUG=${WINEDEBUG:-"fixme-all"}
        export WINEDEBUG
        ;;
    -v) set -x;;
    all) 
        sh winetricks -q vb6run vcrun6;    # vcrun6 for mfc42 for sony_vce
        load_audiolib_mp3_recorder;
        load_dbpoweramp;
        load_dvdshrink;
        load_flickr_uploader;
        load_font_xplorer;
        load_joerg_mm_exporter;
        load_musicmatch9;
        load_newsgator_topstyle_lite;
        load_powerstructure;
        load_roughdraft;
        load_tivo_desktop;
        load_valot_mah_jongg;
        load_valot_shisen_sho;
        load_sony_dve;
        ;;
    dbpoweramp) load_dbpoweramp;;
    dvdshrink) load_dvdshrink;;
    flickr_uploader) load_flickr_uploader;;
    font_xplorer) load_font_xplorer;;
    mahjongg) load_valot_mah_jongg;;
    mmexporter) load_joerg_mm_exporter;;
    musicmatch9) load_musicmatch9;;
    mp3recorder) load_audiolib_mp3_recorder;;
    powerstructure) load_powerstructure;;
    roughdraft) load_roughdraft;;
    shisensho) load_valot_shisen_sho;;
    sony_dve) load_sony_dve;;   # needs mfc42
    tivo_desktop) load_tivo_desktop;;
    topstyle_lite) load_newsgator_topstyle_lite;;

    *) echo Unknown arg $1; usage ; exit 1;;
    esac
    # Provide a bit of feedback
    test "$WINETRICKS_QUIET" = "" && case $1 in 
    -q) echo Setting quiet mode;;
    -v) echo Setting verbose mode;;
    *) echo "Install of $1 done" ;;
    esac
    shift
done

# cleanup
rm -rf "$WINETRICKS_TMP"/*

test "$WINETRICKS_QUIET" = "" && echo migrating-user-1 done. || true

