#!/bin/bash
set -u

declare -A tt
tt[kubelet]="launch containers as per their manifests"
tt[kube-scheduler]="container scheduler"
tt[kube-proxy]="network proxy services"
tt[kube-controller-manager]="kubernetes services"
tt[kube-apiserver]="API for kubernetes orchestration"

D=$(dpkg-parsechangelog -SDate | date "+%B %Y")
V=$(dpkg-parsechangelog -SVersion)
V=${V%%+*}
cd ${1-_build}

for C in kubelet kube-scheduler kube-proxy kube-controller-manager kube-apiserver; do
    cp -v ../docs/admin/$C.md ./
    m="$C.md"

    ## remove garbage:
    perl -pi -E 's{<!--[^->]*-->}{}msg; s{^(######|```|\[!\[Analytics).*$}{}msg; ' "$m"

    ## separate options:
    perl -pi -E 's{^\s+((?:--|-\w,\s)\S+=[^:]*):}{\n**$1**\n}msg;' "$m"

    ## uppercase section names:
    perl -pi -E 's{^##\K#(\s\w+)}{uc($1)}smge;' "$m"

    ## SYNOPSIS is DESCRIPTION:
    perl -pi -E 's{^##\s+\KSYNOPSIS}{DESCRIPTION}smg;' "$m"

    go-md2man -in "$C.md" -out "$C.1"

    ## inject NAME and SYNOPSIS:
    perl -pi -E "s{^\.TH \S+\K}{\n.SH NAME\n$C \- ${tt[$C]}\n\n.SH SYNOPSIS\n$C [OPTIONS]\n}ms;" "$C.1"

    ## correct first line:
    perl -pi -E "s{^\.TH \S+\K}{ \"1\" \"$D\" \"$V\" \"Kubernetes $V\"\n}ms;" "$C.1"
done
