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

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

main() {

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

  rm -f -r *.tmp*

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

  v1=${v%%.*}
  readonly v1

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

  download2 *.urls

  mkdir extract.tmp

  for x in texinfo-$v.tar*; do
    (cd extract.tmp; extract ../$x)
    break
  done
  mv -f extract.tmp/* dist.tmp

  case $v in ([0-5].* | 6.[0-7])
    cp texinfo-6.7.tar.gz texinfo.tmp.tar.gz
  ;; *)
    cp texinfo-$v.tar.gz texinfo.tmp.tar.gz
  esac

  x=$(find dist.tmp -type f -printf '%T@\n' | sort -n | tail -1)
  {
    printf %03d%03d: "$v1" "$v2"
    date -d "@$x" -u +%Y-%m-%d
  } >date

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

  docker build \
    --build-arg v=$v \
    --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

  >files
  for x in out.tmp/*; do
    sed '
      s|</head>|\
<script defer src="notice.js"></script>\
&|
      s|</head>|\
<script defer src="qref.js"></script>\
&|
    ' $x >$x.tmp
    mv -f $x.tmp $x
    echo ${x#out.tmp/} >>files
  done

  mv -f out.tmp/* .

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

}; readonly -f main

main "$@"
