#! /bin/sh

set -e

printlist()
{
  for e in "$@"; do
    echo "    $e"
  done
}

myname=$(basename $0)
mydir=$(dirname $0)

opt_d=false

for p in "$@"; do
  # destdir should be the last
  if [ -n "$destdir" ]; then
    packages=""
    break
  fi

  case "$p" in
    -d)
      opt_d=true
      ;;
    *)
      if $opt_d; then
        destdir="$p"
        opt_d=false
      else
        packages="$packages${packages:+ }$p"
      fi
      ;;
  esac
done

if [ -z "$packages" ] || $opt_d ; then
  echo "Usage: $myname URL_for_ZIP ... [-d destdir]"
  echo
  echo "This will install the ZIPs to destdir."
  echo "If destdir is omitted, destdir will be i686-pc-os2-emx of" \
       "the parent dir of"
  echo "the dir where $myname is. That is, dir/../i686-pc-os2-emx."
  exit 1
fi

# assume we're in /opt/os2emx/bin directory
prefix=$mydir/..
target=i686-pc-os2-emx
targetprefix=${destdir:-"$prefix/$target"}

: ${CURL:=curl -sSfL}
: ${SED:=sed -E}
: ${UNZIP:=unzip}
: ${MKDIR_P:=mkdir -p}
: ${CP:=cp -v}
: ${RM:=rm -f}

zipdir="$myname.zip.dir"

$MKDIR_P "$zipdir"

curlopts=""
for zipurl in $packages; do
  case "$zipurl" in
    *://*)
      ;;
    *)
      if [ -f "$zipurl" ]; then
        # add local files
        z="$zipurl"
        if [ -n "${z##/*}" ]; then
          # relative path
          z="$(pwd)/$z"
        fi
        zipurl="file://$z"
      fi
      ;;
  esac

  zipurls="$zipurls${zipurls:+ }$zipurl"
  curlopts="$curlopts${curlopts:+ }-O -J $zipurl"
done

echo "Downloading the ZIPs..."
printlist $zipurls
zips="$($CURL --clobber -w "%{filename_effective}\n" --output-dir "$zipdir" $curlopts \
        | $SED "s,$zipdir/,,g")"

echo "Unzipping the ZIPs..."
printlist $zips
zipprefixes=""
for zip in $zips; do
  $UNZIP -u "$zipdir/$zip" -d "$zipdir/$zip.dir"

  # find prefix of the ZIP
  while read -r s d t p; do
    case "$p" in
      */bin/ | */include/ | */lib/ | */lib64/ | */share/)
        zipprefixes="$zipprefixes${zipprefixes:+ }/$zip.dir/${p%/*/}"
        break
        ;;
      bin/ | include/ | lib/ | lib64/ | share/)
        zipprefixes="$zipprefixes${zipprefixes:+ }/$zip.dir"
        break
        ;;
    esac
  done << EOF
$($UNZIP -qql "$zipdir/$zip")
EOF
done

echo "Installing the unzipped file(s) into $targetprefix..."
$MKDIR_P "$targetprefix"
for zipprefix in $zipprefixes; do
  for d in "$zipdir$zipprefix"/* ; do
    if [ -d "$d" ] ; then
      $CP -fa "$d" "$targetprefix" || break
    fi
  done
done

echo "Cleaning up..."
$RM -r "$zipdir"
