#! /bin/sh

set -e

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

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

opt_d=false
opt_e=false

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

  case "$p" in
    -d)
      opt_d=true
      ;;
    -e)
      opt_e=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 package[_oc00[.zip]] ... [-e] [-d destdir]"
  echo
  echo "This will install package[_oc00[.zip] to destdir."
  echo "If -e is given, experimental repo will be searched, too."
  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}
: ${SORT:=sort}
: ${GREP:=grep}
: ${UNZIP:=unzip}
: ${MKDIR_P:=mkdir -p}
: ${CP:=cp -v}
: ${RM:=rm -f}

zipurl="https://rpm.netlabs.org/release/00/zip"
zipexpurl="https://rpm.netlabs.org/experimental/00/zip"
zipdir="$myname.zip.dir"
ziplst="$zipdir/$myname.zip.lst"

$MKDIR_P "$zipdir"

echo "Downloading the ZIP file list..."
$CURL "$zipurl/" \
  | $SED -n -e "s/^.*href=\"\(.*\.zip\)\".*$/\1@@@rel@@@/" \
            -e "/^pthread.*-20[0-9]*-[0-9][0-9]*[-_.].*$/!p" > "$ziplst.tmp"

if $opt_e; then
  $CURL "$zipexpurl/" \
    | $SED -n -e "s/^.*href=\"\(.*\.zip\)\".*$/\1@@@exp@@@/p" >> "$ziplst.tmp"
fi

$SORT -V < "$ziplst.tmp" > "$ziplst"
$RM "$ziplst.tmp"

addpackage()
{
  z="${1%@@@rel@@@}"
  z="${z%@@@exp@@@}"
  zips="$zips $z"

  case "$1" in
    *".zip@@@rel@@@")
      z="$zipurl/$z"
      ;;
    *".zip@@@exp@@@")
      z="$zipexpurl/$z"
      ;;
  esac

  curlopts="$curlopts${curlopts:+ }-O -J $z"
  return 0
}

echo "Checking the package(s)..."
printlist $packages
for package in $packages; do
  case "$package" in
    *://*)
      # add URLs
      addpackage "$package"
      continue
      ;;
    *'*'* | *'?'*)
      pname=""
      z=""
      while read -r l; do
        case "$l" in
          $package)
            pn=$(echo "$l" | $SED 's/[-_.][0-9][0-9]*[-_.].*//')
            if [ "$pname" != "$pn" ]; then
              [ -z "$pname" ] || addpackage "$z"
              pname="$pn"
            fi
            z="$l"
            ;;
        esac
      done < "$ziplst"
      [ -n "$pname" ] || { echo "Package '$package' not found!"; exit 1; }

      addpackage "$z"
      continue
      ;;
    *)
      if [ -f "$package" ]; then
        # add local files
        p="$package"
        if [ -n "${p##/*}" ]; then
          # relative path
          p="$(pwd)/$p"
        fi
        p="file://$p"
        addpackage "$p"
        continue
      fi
      ;;
  esac

  # normalize package
  z=${package%.zip}
  z=${z%_oc00}
  z="${z}_oc00.zip"

  # find the exact match first
  z=$($GREP "^$z@@@\(rel\|exp\)@@@$" $ziplst) || :

  if [ -z "$z" ]; then
    # find the latest version with $package package name
    z=$($GREP "^${package}[-_][0-9]" $ziplst | tail -n1) || :

    [ -n "$z" ] || { echo "Package '$package' not found!"; exit 1; }
  fi

  addpackage "$z"
done

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

echo "Unzipping the ZIP(s)..."
printlist $zips
for z in $zips; do
  $UNZIP -u "$zipdir/$z" -d "$zipdir"
done

echo "Installing the unzipped file(s) to $targetprefix..."
$MKDIR_P "$targetprefix"
for d in "$zipdir/@unixroot/usr"/* ; do
  $CP -fa "$d" "$targetprefix" || break
done

echo "Postprocessing for the ZIP(s)..."
postrpm "$targetprefix"

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