#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o pipefail
if [[ "${TRACE-0}" == "1" ]]; then
    set -o xtrace
fi

if [[ "${1-}" =~ ^-*h(elp)?$ ]]; then
    echo 'Usage: hack/make/docs

This script generates markdown docs from cli.

'
    exit
fi

require_sandbox() {
    if [[ ! -d pkg/sandbox ]]; then
        echo "ERROR: pkg/sandbox/ is closed-source and not present in public clones." >&2
        echo "       CLI doc generation requires the sandbox command sources." >&2
        echo "       Public users should use the committed docs instead of regenerating them." >&2
        exit 1
    fi
}

move_swagger() {
    if [[ -f api/swagger.json ]]; then
        cp api/swagger.json www/static/api/swagger.json
    fi
}

main() {
    require_sandbox
    move_swagger

    SED="sed"
    if which gsed >/dev/null 2>&1; then
        SED="gsed"
    fi

    rm -rf www/docs/cli/**/*.md
    go run -tags 'sandbox' ./cmd/ipsw/main.go docs
    # go run . schema -o ./www/docs/static/schema.json
    fd .md www/docs/cli/ | xargs $SED -i'' \
        -e ':a' -e 'N' -e '$!ba' -e 's/### Examples\n\n```/### Examples\n\n```bash/g'
    #     -e 's/^## /# /g' \
    #     -e 's/^### /## /g' \
    #     -e 's/^#### /### /g' \
    #     -e 's/^##### /#### /g'
}

main "$@"
