#!/usr/bin/env bash

# https://github.com/cirosantilli/china-dictatorship#mirrors

set -eux

echo $#
if [ $# -gt 0 ]; then
  dry_run=true
else
  dry_run=false
fi
make
make multipage
if ! $dry_run; then
  git push --follow-tags
  git push -f git@github.com:cirosantilli/china-dictatorship-2.git &
  git push -f git@gitlab.com:cirosantilli/china-dictatorship.git &
  git push -f git@github.com:R7w726fYrfritM7zPJCO/cihna-dictatorshrip-8.git &
  git push -f git@gitlab.binets.fr:ciro.duran-santilli/china-dictatorship.git &
  wait
fi

out_dir=out
out_multipage_dir="${out_dir}/multipage"

function multipage-fixup() (
  # Ain't nobody got time for Ruby coding!!!
  # https://github.com/owenh000/asciidoctor-multipage/issues/20
  # https://github.com/owenh000/asciidoctor-multipage/issues/21
  # https://github.com/owenh000/asciidoctor-multipage/issues/22
  find "$1" -name '*.html' ! -name 'index.html' | xargs perl -lapi -e '
s/<h[2-6] id="/<h2 id="/g;
s/href="README.html"/href="index-split"/g;
s/(href="(?![^"]+:\/\/)[^"]+).html(#[^"]*)?"/\1\2"/g;
'
  # Not possible, it is identical to other lists actually...
  # s/(<div class="paragraph nav-footer">)/<h2>Table of contents<\/h2>\1/g;
)

# GitHub pages.
# One time initial setup.
# git checkout --orphan gh-pages
# and copy over https://github.com/cirosantilli/jekyll-min
gh_pages_dir="${out_dir}/gh-pages"
if [ ! -d "$gh_pages_dir" ]; then
  mkdir -p "$gh_pages_dir"
  git clone --branch gh-pages --depth 1 "$(git remote get-url origin)" "$gh_pages_dir"
fi
cp README.html "${gh_pages_dir}/index.html"
cp "${out_multipage_dir}/"* "$gh_pages_dir"
mv "${gh_pages_dir}/README.html" "${gh_pages_dir}/index-split.html"
multipage-fixup "$gh_pages_dir"
if ! $dry_run; then
  git -C "$gh_pages_dir" add .
  if git -C "$gh_pages_dir" commit -m "$(git log -1 --format="%H")"; then
    git -C "$gh_pages_dir" push -f
  fi
fi

# GitLab pages
gl_pages_dir="${out_dir}/gl-pages"
gl_pages_public_dir="${gl_pages_dir}/public"
if [ ! -d "$gl_pages_dir" ]; then
  mkdir -p "${out_dir}"
  git clone --branch gl-pages --depth 1 git@gitlab.com:cirosantilli/china-dictatorship.git "$gl_pages_dir"
fi
make MEDIA=https://gitlab.com/cirosantilli/china-dictatorship-media/-/raw/master OUT="${gl_pages_public_dir}/index.html"
cp .gitlab-ci.yml "${gl_pages_dir}"
cp "${out_multipage_dir}/"* "$gl_pages_public_dir"
mv "${gl_pages_public_dir}/README.html" "${gl_pages_public_dir}/index-split.html"
multipage-fixup "$gl_pages_public_dir"
if ! $dry_run; then
  git -C "$gl_pages_dir" add .
  if git -C "$gl_pages_dir" commit -m "$(git log -1 --format="%H")"; then
    git -C "$gl_pages_dir" push -f
  fi
fi
