#!/bin/sh

TMPDIR="/tmp/netflix-install"
LOGFILE="$TMPDIR/netflix-install.log"

if [ ! -d "$TMPDIR" ]
then
 mkdir $TMPDIR
fi
 
cd $TMPDIR

mkdir fonts
mkdir cab-contents

download_files="andale32.exe arial32.exe arialb32.exe comic32.exe courie32.exe georgi32.exe impact32.exe times32.exe trebuc32.exe webdin32.exe verdan32.exe wd97vwr32.exe"

### MD5 Sums
andale32_md5="cbdc2fdd7d2ed0832795e86a8b9ee19a  andale32.exe"
arial32_md5="9637df0e91703179f0723ec095a36cb5  arial32.exe"
arialb32_md5="c9089ae0c3b3d0d8c4b0a95979bb9ff0  arialb32.exe"
comic32_md5="2b30de40bb5e803a0452c7715fc835d1  comic32.exe"
courie32_md5="4e412c772294403ab62fb2d247d85c60  courie32.exe"
georgi32_md5="4d90016026e2da447593b41a8d8fa8bd  georgi32.exe"
impact32_md5="7907c7dd6684e9bade91cff82683d9d7  impact32.exe"
times32_md5="ed39c8ef91b9fb80f76f702568291bd5  times32.exe"
trebuc32_md5="0d7ea16cac6261f8513a061fbfcdb2b5  trebuc32.exe"
webdin32_md5="230a1d13a365b22815f502eb24d9149b  webdin32.exe"
verdan32_md5="12d2a75f8156e10607be1eaa8e8ef120  verdan32.exe"
wd97vwr32_md5="efa72d3ed0120a07326ce02f051e9b42  wd97vwr32.exe"

function check_file {
  matches=
  if [ ! -r $1 ]
  then
    echo "Need to download [$1]"
    return
  fi
  local variable_name=`basename $1 .exe`_md5
  local stored_checksum
  eval stored_checksum=\$$variable_name
  local computed_checksum=`md5sum $1`
  if [ "$stored_checksum" = "$computed_checksum" ]
  then
    echo "Verified font package: [$f]."
    matches=yes
  else
    rm $1
    matches=
  fi
}

function download_cf {
  echo "Downloading font package: [$1]"
  wget -O "$1" http://sourceforge.net/projects/corefonts/files/the%20fonts/final/$1/download >>$LOGFILE 2>&1
}

function extract_cf {
  echo "Extracting fonts from: [$1]"
  cabextract --lowercase --directory=cab-contents $1 >>$LOGFILE 2>&1
  if [ -e "cab-contents/viewer1.cab" ]
  then
    cabextract --lowercase --directory=cab-contents cab-contents/viewer1.cab >>$LOGFILE 2>&1
  fi
  cp cab-contents/*.ttf fonts
  rm -f cab-contents/*
}

for f in $download_files
do
  check_file $f
  while [ ! $matches ]
  do
    download_cf $f
    check_file $f
    if [ ! $matches ]
    then
      echo "Failed to download: [$f]"
      failures=`expr $failures + 1`
      if [ $failures -gt 5 ]
      then
        echo "Failed to download [$f] too many times."
        exit 1
      fi
      echo "Retrying [$f] from SourceForge."
    fi
  done
  extract_cf $f
done

if [[ ${EUID} == 0 ]] ; then
  echo "Installing as system wide fonts."
  if [ ! -d "/usr/share/fonts/msttcorefonts" ]
  then
    mkdir -p /usr/share/fonts/msttcorefonts
  fi
  mv -f fonts/* /usr/share/fonts/msttcorefonts
  cd /usr/share/fonts/msttcorefonts
  /usr/bin/ttmkfdir >fonts.dir
  cd $TMPDIR
else
  echo "Installing for user [$USERNAME]."
  if [ ! -d "$HOME/.fonts" ]
  then
    mkdir -p $HOME/.fonts
  fi
  mv -f fonts/* $HOME/.fonts
fi
/usr/bin/fc-cache

### End MSTTCoreFonts Installation


