#!/bin/sh
U=http://maclasse.plumppu.nu/bs.pkg
F=InstallAssistant.pkg
cd ~/Downloads || exit 1

# Size of the file on the server
R=$(curl -sfI "$U" | awk 'tolower($1)=="content-length:"{gsub("\r","");print $2}')
[ -n "$R" ] || { echo "Can't reach server or file missing"; exit 1; }

# Adopt a bs.pkg from an earlier curl -O attempt
[ -f bs.pkg ] && [ ! -f "$F" ] && mv bs.pkg "$F"
rm -f bs.pkg

# Validate any existing download
if [ -f "$F" ]; then
  L=$(stat -f%z "$F")
  head -c 65536 "$F" > /tmp/bs_local
  curl -sf -r 0-65535 "$U" > /tmp/bs_remote
  if [ "$L" -gt "$R" ] || ! cmp -s /tmp/bs_local /tmp/bs_remote; then
    echo "Existing $F doesn't match server file, deleting."; rm -f "$F"
  elif [ "$L" -eq "$R" ] && ! pkgutil --check-signature "$F" >/dev/null 2>&1; then
    echo "Existing $F is full size but fails signature check, deleting."; rm -f "$F"
  elif [ "$L" -lt "$R" ]; then
    echo "Resuming partial download ($L of $R bytes)."
  fi
  rm -f /tmp/bs_local /tmp/bs_remote
fi

# Download with auto-resume
n=0
while [ ! -f "$F" ] || [ "$(stat -f%z "$F")" -lt "$R" ]; do
  curl -f -C - -o "$F" "$U" && break
  n=$((n+1)); [ $n -ge 50 ] && { echo "Giving up after 50 tries"; exit 1; }
  echo "Connection dropped, resuming in 5 s (try $n)..."; sleep 5
done

[ "$(stat -f%z "$F")" -eq "$R" ] || { echo "Size mismatch after download, rerun the script."; exit 1; }
pkgutil --check-signature "$F" && open "$F"
