#!/bin/sh

# Default to ENU if nothing passed in as first arg
if [ ".$1" == "." ]; then WINLANG="ENU"; else WINLANG="$1"; fi

# Look for URL|LANG in scripts/ + second arg
for needed in `egrep -hri "URL\|($WINLANG|ALL)" scripts/$2 | tr ' ' '~'`; do
    url=`echo "$needed" | cut -d\| -f3 | tr '~' ' ' | perl -pe 's/\r//;s/^ *//;s/ *$//'`
    file=`echo "$needed" | cut -d\| -f4 | tr '~' ' '  | perl -pe 's/\r//;s/^ *//;s/ *$//'`
    path=`echo "$file" | perl -pe 's#(.*/).*#$1#'`

    # Make sure path is available
    mkdir -p "$path"
    # Download file if it doesn't exist
    if [ ! -f "$file" ]; then 
        wget --passive-ftp -O "$file" "$url"
    fi
done

# look for UNZIP|LANG in scripts/ + second arg
for needed in `egrep -hri "UNZIP\|($WINLANG|ALL)" scripts/$2 | tr ' ' '~'`; do
  file=`echo "$needed" | cut -d\| -f3 | perl -pe 's/\r//;s/^ *//;s/ *$//'`
  path=`echo "$file" | sed "s/\(.*\)\/[^\/]*/\1/"`
  unzip $file -d $path
done

# look for MD5|LANG in scripts/ + second arg
for needed in `egrep -hri "MD5\|($WINLANG|ALL)" scripts/$2 | tr ' ' '~'`; do
  file=`echo "$needed" | cut -d\| -f3 | perl -pe 's/\r//;s/^ *//;s/ *$//'`
  corrmd5=`echo "$needed" | cut -d\| -f4 | perl -pe 's/\r//;s/^ *//;s/ *$//'`
  filemd5=`cat $file | md5`
  if [ X"$corrmd5" != X"$filemd5" ]; then
    echo $file has an incorrect md5. aborting.
    exit
  fi
done
