#! /bin/sh -
#
# This file is licensed under the MIT No Attribution license.
#

set -e || exit $?
. ./prelude.bash

main() {

  declare    archive
  declare    container
  declare    image
  declare    v
  declare    v1
  declare    v2
  declare    x

  rm -f -r *.tmp*

  v=${PWD##*/}
  readonly v

  v1=${v%%.*}
  v2=${v#"$v1."}
  v2=${v2%%[.-]*}
  v2=${v2%%[a-z]*}

  download2 *.urls

  case $v in
    1.07) archive=groff-1.06.tar.gz ;;
    1.11) archive=groff-1.10.tar.gz ;;
    1.02 | 1.04 | 1.05) archive=groff-$v.tar.Z ;;
    *) archive=groff-$v.tar.gz ;;
  esac

  mkdir extract.tmp
  (cd extract.tmp; extract ../"$archive")
  mv extract.tmp/* dist.tmp

  case $v in
    1.07)
      mv dist.tmp/CHANGES dist.tmp/NEWS
      mv dist.tmp/devps/prologue dist.tmp/devps/prologue.ps
      mv dist.tmp/troff/hyphen dist.tmp/troff/hyphen.us
    ;;
  esac
  for x in groff-*.diff.gz; do
    gzip -cd "$x" | (cd dist.tmp; patch --force --set-utc --remove-empty-files -p1)
  done

  # Sort by major/minor release family, then by the source date. This
  # also puts the unusually named 2018 1.22.3.rc1 after 2014's 1.22.3.
  x=$(find dist.tmp -type f -printf '%T@\n' | sort -n | tail -1)
  {
    printf %03d%03d: "$((10#$v1))" "$((10#$v2))"
    date -d "@$x" -u +%Y-%m-%d
  } >date
  printf '%s\n' "${x%.*}" >dist.tmp/source-date-epoch.tmp

  for x in *.bash *.patch *.py; do
    cp "$x" "$x.tmp"
  done

  docker build --iidfile image.tmp -f - . <Dockerfile
  image=$(cat image.tmp)
  readonly image

  container=$(docker create "$image")
  readonly container

  mkdir out.tmp
  docker cp "$container":/out.tmp/. out.tmp
  if [[ -f files ]]; then
    while IFS= read -r x; do
      rm -f -- "$x"
    done <files
  fi
  rm -f -r images
  for x in out.tmp/*; do
    if [[ -d $x && -d ${x#out.tmp/} ]]; then
      rm -r -- "${x#out.tmp/}"
    fi
    mv "$x" .
  done

  rm -f -r *.tmp*
  docker rm -f "$container"

}; readonly -f main

main "$@"
