#!/bin/bash

export PATH=$PATH:/opt/wine-stable/bin
export WINEPREFIX="${XDG_DATA_HOME:-"$HOME/.local/share"}/cncnet"

LAUNCHER="$WINEPREFIX/drive_c/Games/CnCNet/CnCNetLauncher.exe"
INSTALLER="$WINEPREFIX/drive_c/CnCNet.exe"
INSTALLERURL="https://downloads.cncnet.org/CnCNet.exe"
INSTALLERARGS="/NOSHORTCUTS /SILENT"



DOWNLOAD() {

  if [ -x "$(command -v wget)" ]; 
  then 
    if [ -x "$(command -v zenity)" ]; 
    then

      rand="$RANDOM `date`"
      pipe="/tmp/pipe.`echo '$rand' | md5sum | tr -d ' -'`"
      mkfifo $pipe
      wget "$1" -O "$2" 2>&1 | while read data;do
        if [ "`echo $data | grep '^Length:'`" ]; then
          total_size=`echo $data | grep "^Length:" | sed 's/.*\((.*)\).*/\1/' |  tr -d '()'`
        fi
        if [ "`echo $data | grep '[0-9]*%' `" ];then
          percent=`echo $data | grep -o "[0-9]*%" | tr -d '%'`
          current=`echo $data | grep "[0-9]*%" | sed 's/\([0-9BKMG.]\+\).*/\1/' `
          speed=`echo $data | grep "[0-9]*%" | sed 's/.*\(% [0-9BKMG.]\+\).*/\1/' | tr -d ' %'`
          remain=`echo $data | grep -o "[0-9A-Za-z]*$" `
          echo $percent
          echo "#Downloading $1\n$current of $total_size ($percent%)\nSpeed : $speed/Sec\nEstimated time : $remain"
        fi
      done > $pipe &
     
      wget_info=`ps ax |grep "wget.*$1" |awk '{print $1"|"$2}'`
      wget_pid=`echo $wget_info|cut -d'|' -f1 `
     
      zenity --progress --auto-close --text="Connecting to $1\n\n\n" --width="350" --title="Downloading"< $pipe
      if [ "`ps -A |grep "$wget_pid"`" ];then
        kill $wget_pid
      fi
      rm -f $pipe

    else
      wget "$1" -O "$2"
    fi
  else
    curl "$1" -o "$2"
  fi
}


if [ ! -f "$LAUNCHER" ];
then
    WINEARCH=win32 WINEDLLOVERRIDES="mscoree,mshtml=" wine wineboot
    DOWNLOAD "$INSTALLERURL" "$INSTALLER"
    wine "$INSTALLER" $INSTALLERARGS
fi
    taskset -c 0 wine "$LAUNCHER"


