#!/usr/bin/env bash

set -e

: "${PERL:=$(which perl)}"

rm -fr cpan
mkdir cpan

CP_RL='cp -rL'
if [[ "$OSTYPE" =~ ^darwin|^freebsd ]]; then
  CP_RL='cp -r'
fi

(
  set -x
  cp Changes cpan
  # XXX Maybe should be CONTRIBUTING.pod
  [ -e Contributing ] && cp Contributing cpan/CONTRIBUTING
  [ -e bin ] && cp -r bin cpan
  [ -e eg ] && cp -r eg cpan/example
  cp -r lib cpan
  [ -e share ] && $CP_RL share cpan
  cp -r test cpan/t
  if [ -d cpan/t/extra ]; then
    mv cpan/t/extra cpan/xt
  elif [ -d cpan/t/devel ]; then
    mv cpan/t/devel cpan/xt
  fi
  rm -fr cpan/t/misc cpan/t/fail

  $PERL -S zild-render-template dist.ini cpan/dist.ini
)
[ -x tool/make-cpan ] && tool/make-cpan

for swim in $(find doc -type f -name '*.swim'); do
  pod="${swim/doc/cpan/lib}"
  pod="${pod/.swim/.pod}"
  mkdir -p "$(dirname "$pod")"
  if grep '^====' "$swim" &> /dev/null; then
    (
      set -x
      swim --to=pod --pod-cpan "$swim" > "$pod"
    )
  else
    (
      set -x
      swim --to=pod --complete --wrap "$swim" > "$pod"
    )
  fi
done

alias="$($PERL -S zild meta =cpan/alias)"
if [ -n "$alias" ]; then
  for a in "${alias[@]}"; do
    $PERL -S zild-render-template
  done
fi

if [ -e pkg/make-cpan ]; then
  ./pkg/make-cpan
fi

# vim: set sw=2 lisp: