#!/bin/bash

# Author: King Eca https://easiestsoft.com
# Date: 2019-12-21

fxz=src.xz
sshost=host-easiestsoft

cd ~/mybook/easiestsoft.com
rm --force $fxz
tar --create --xz --file=$fxz $(fd --changed-within 1d --exclude 'zz_*' -E '*.xz' --type file --path-separator '//')
ls -l --human-readable $fxz

sftp $sshost:/home/easiestsoft.com/mdbook <<< $"put $fxz"

ssh $sshost <<'ENDSSH'
	book=/home/easiestsoft.com/mdbook
	public=/home/easiestsoft.com/public
	out=~/out-mdbook
	fxz=src.xz

    cd $book
    tar --extract --xz --file=$fxz
    rm --force $fxz

    mdbook build --dest-dir $out
    cd $out
    fd -0 --extension html | xargs -0 sd --string-mode 'index.html"' '"'
    fd -0 --extension html | xargs -0 sd '(?:<[^>]+>){2}~-[\w\s_/-]+?-~</a></li>' ''
    fd -0 --extension html | xargs -0 sd '(<title>)~-([\w\s_/-]+?)-~' '$1$2'
    sd --string-mode '../' 'https://easiestsoft.com/' z/not-found.html

    # Suppose we don't use any puglins for mdBook
    # if we use a plugin, we should use `$out/html/*` instead of `$out/*`
    cp --recursive $out/* $public
    rm --recursive --force $out
ENDSSH

rm --force $fxz