#!/bin/sh
# Usage: ssg.sh GITDIR OUTDIR [DESCRIPTION]
set -eu

if [ $# -lt 2 ]; then
    echo "usage: $0 GITDIR OUTDIR [DESCRIPTION]" >&2
    exit 1
fi
repo=$1
out=$2
desc=${3:-}
files=$out/files
raw=$out/raw
tpl=${DIR_TEMP:-templates}
tab=$(printf '\t')

# The repo's name is its directory name, without .git.
reponame=$(cd "$repo" && pwd -P)
reponame=${reponame%/.git}
reponame=${reponame##*/}
reponame=${reponame%.git}

g() { git -C "$repo" -c core.quotePath=false "$@"; }

# Escape HTML special characters: escape filters stdin, esc takes a string.
escape() { sed 's/&/\&amp;/g; s/</\&lt;/g; s/>/\&gt;/g; s/"/\&quot;/g'; }
esc() { printf '%s\n' "$1" | escape; }

# Link targets: percent-encode anything that would break a relative URL.
href() { printf '%s\n' "$1" | sed 's/%/%25/g; s/ /%20/g; s/#/%23/g; s/?/%3F/g; s/&/%26/g; s/</%3C/g; s/>/%3E/g; s/"/%22/g'; }

heading=$(esc "$reponame${desc:+ - $desc}")

# page top|bottom: print the part of page.html before or after the
# {{CONTENT}} line, with {{TITLE}}, {{HEADER}} and {{FOOTER}} filled in.
page() {
    T='{{TITLE}}' H='{{HEADER}}' F='{{FOOTER}}' C='{{CONTENT}}'
    part=top
    while IFS= read -r line || [ -n "$line" ]; do
        case $line in *"$C"*) part=bottom; continue ;; esac
        [ "$part" = "$1" ] || continue
        case $line in
        *"$T"*) printf '%s%s%s\n' "${line%%"$T"*}" "$title" "${line#*"$T"}" ;;
        *"$H"*) printf '%s' "${line%%"$H"*}"; cat "$tpl/header.html"; printf '%s\n' "${line#*"$H"}" ;;
        *"$F"*) printf '%s' "${line%%"$F"*}"; cat "$tpl/footer.html"; printf '%s\n' "${line#*"$F"}" ;;
        *)      printf '%s\n' "$line" ;;
        esac
    done < "$tpl/page.html"
}

# Start a page: the top of page.html, then the repo name, description and
# nav that every page shares. Needs $title, and $root leading back to $out.
begin() {
    page top
    printf '<h1 class="repo-title">%s</h1>\n' "$(esc "$reponame")"
    printf '<div>%s</div>\n' "$(esc "$desc")"
    printf '<div>git clone https://jhhm.no/repos/%s.git</div>\n' "$(esc "$reponame")"
    printf '<nav class="repo-nav">\n'
    printf '<a href="%s">about</a>\n<a href="%sfiles/">files</a>\n<a href="%slog/">log</a>\n' \
        "$root" "$root" "$root"
    printf '</nav>\n'
}

# item LABEL LINK: one entry in a listing.
item() { printf '<li><a href="./%s">%s</a></li>\n' "$(href "$2")" "$(esc "$1")"; }

# A file as escaped monospace text.
text() { printf '<pre>'; escape < "$1"; printf '</pre>\n'; }

# Page content for one file. $1 is its raw copy, $mode its git mode.
render() {
    if [ "$mode" = 120000 ]; then
        text "$1"                         # a symlink: the path it points to
    elif ! tr -d '\000' < "$1" | cmp -s - "$1"; then
        echo '<p>&ltbinary data&gt</p>'         # removing NUL bytes changed it
    else
        # "sed =" prints each line's number on a line of its own,
        # the second sed joins the number onto the line after it.
        printf '<pre>'
        escape < "$1" | sed = | sed 'N; s/^\([0-9]*\)\n/<span class="ln">\1<\/span>/'
        printf '</pre>\n'
    fi
}

# Where repo path $1 goes under files/. A component named index.html would
# clash with the listing of its directory, so it gets an "_" appended; any
# component that is "index.html" plus only underscores gets one more, so
# a real "index.html_" can't clash either.
outpath() {
    p= rest=$1
    while [ -n "$rest" ]; do
        c=${rest%%/*}
        case $rest in */*) rest=${rest#*/} ;; *) rest= ;; esac
        case $c in
            index.html*) case ${c#index.html} in *[!_]*) ;; *) c=${c}_ ;; esac ;;
        esac
        p=${p:+$p/}$c
    done
    printf '%s\n' "$p"
}

# Set $root to the relative link from directory $1 (inside $out) to $out.
up() {
    root= d=$1
    while :; do
        root=../$root
        case $d in */*) d=${d%/*} ;; *) break ;; esac
    done
}

# entries DIR PREFIX: the <li> items for repo directory DIR ("" for the
# root), linking to PREFIX + the entry's page. Directories have mode 040000
# and everything else starts with 1, so sorting on the mode's first
# character puts directories first, then by name.
entries() {
    g ls-tree "HEAD:$1" | LC_ALL=C sort -t "$tab" -k1.1,1.1 -k2 |
    while IFS=$tab read -r meta name; do
        case $name in \"*) continue ;; esac
        case $meta in
            040000*) label=$name/ ;;
            160000*) continue ;;          # submodules
            *) label=$name ;;
        esac
        item "$label" "$2$(outpath "$name")/"
    done
}

# Write the listing page for repo directory $1 ("" for the root).
listing() {
    o=$(outpath "$1")
    title=$(esc "$reponame/${1:+$1/}")
    up "files${o:+/$o}"
    mkdir -p "$files/$o"
    {
        begin
        printf '<h2 class="repo-path">%s</h2>\n<ul>\n' "$title"
        [ -z "$1" ] || echo '<li><a href="../">../</a></li>'
        entries "$1" ""
        echo '</ul>'
        page bottom
    } > "$files/${o:+$o/}index.html"
}

mkdir -p "$raw"
listing ""

g ls-tree -r -t HEAD | while IFS=$tab read -r meta path; do
    set -- $meta
    mode=$1 type=$2 sha=$3

    case $path in
        \"*) printf 'skipping weird filename: %s\n' "$path" >&2; continue ;;
    esac

    case $type in
    tree)
        mkdir -p "$raw/$path"
        listing "$path"
        ;;
    blob)
        g cat-file blob "$sha" > "$raw/$path"
        opath=$(outpath "$path")
        up "files/$opath"
        title=$(esc "$reponame/$path")
        mkdir -p "$files/$opath"
        {
            begin
            printf '<h2 class="repo-path">%s</h2>\n' "$title"
            printf '<p>get raw file: <a href="%sraw/%s">%s</a></p>\n' "$root" "$(href "$path")" "$(basename "$(esc "$path")")"
            render "$raw/$path"
            page bottom
        } > "$files/$opath/index.html"
        ;;
    esac
done

# The log page: the latest 50 commits, then a count of the rest. The
# subject goes last in git's output so a tab inside it can't shift the
# columns. The full subject is also in a title attribute, so it shows on
# hover when the CSS cuts it short.
title=$(esc "$reponame/log") root=../
more=$(($(g rev-list --count HEAD) - 50))
mkdir -p "$out/log"
{
    begin
    echo '<table class="log">'
    echo '<colgroup><col class="date"><col class="message"><col class="author"></colgroup>'
    echo '<tr><th>Date</th><th>Message</th><th>Author</th></tr>'
    g log -n 50 --date=short --format='%ad%x09%an%x09%s' | escape |
    while IFS=$tab read -r date author subject; do
        printf '<tr><td>%s</td><td title="%s">%s</td><td>%s</td></tr>\n' \
            "$date" "$subject" "$subject" "$author"
    done
    echo '</table>'
    if [ "$more" -gt 0 ]; then
        printf '<p>And a whopping %s more can be fetched!</p>\n' "$more"
    fi
    page bottom
} > "$out/log/index.html"

# The homepage: the top of the tree (at most 10 entries), then the first
# regular file (mode 100...) called README or README.*.
list=$(entries "" files/)
n=$(($(printf '%s\n' "$list" | wc -l)))
readme=$(g ls-tree HEAD | while IFS=$tab read -r meta name; do
    case $meta:$name in
    100*:[Rr][Ee][Aa][Dd][Mm][Ee]|100*:[Rr][Ee][Aa][Dd][Mm][Ee].*)
        printf '%s\n' "$name"
        break ;;
    esac
done)

title=$(esc "$reponame") root=./
{
    begin
    # echo '<h2>files</h2>'
    echo '<ul class="repo-filelist">'
    printf '%s\n' "$list" | head -n 10
    if [ "$n" -gt 10 ]; then
        echo '<li><a href="./files/">... view all items</a></li>'
    fi
    echo '</ul>'
    case $readme in
        '') ;;
        *.md|*.markdown) markup < "$raw/$readme" ;;
        *) text "$raw/$readme" ;;
    esac
    page bottom
} > "$out/index.html"
