#!/bin/sh

# SPDX-FileCopyrightText: Huawei Inc.
#
# SPDX-License-Identifier: Apache-2.0

set -e

DEFAULT_COPYRIGHT="Huawei Inc."
DOCS_LICENSE="CC-BY-4.0"
TOOL_DEPS="\
    pandoc \
    reuse \
    "

help() {
    cat << EOF
CONTRIBUTING.sh

Tool to populate a CONTRIBUTING.md file.

Options:
  -h, --help
    Display this help information and exit.

  -c, --copyright COPYRIGHT
    Copyright statement.
    Defaults to: "$DEFAULT_COPYRIGHT".

  -o, --output FILE|DIR
    Output file. If directory is given, the output will a CONTRIBUTING.md file
    in the requested directory.
    Required argument.

Tool dependencies:
EOF
for tool in $TOOL_DEPS; do
    echo "  - $tool"
done
}

log() {
    # Address log levels
    case $1 in
        ERROR)
            loglevel=ERROR
            shift
            ;;
        WARN)
            loglevel=WARNING
            shift
            ;;
        *)
            loglevel=LOG
            ;;
    esac
    printf "[%s] %s\n" "$loglevel" "$1"
    [ "$loglevel" != "ERROR" ] || exit 1
}

# Parse arguments
while [ "$#" -ge 1 ]; do
    i="$1"
    case $i in
        -h|--help)
            help
            exit 0
            ;;
        -c|--copyright)
            [ -n "$2" ] || log ERROR "\"$1\" argument needs a value. See help information."
            COPYRIGHT="$2"
            shift
            ;;
        -o|--output)
            [ -n "$2" ] || log ERROR "\"$1\" argument needs a value. See help information."
            OUT="$2"
            [ ! -d "$OUT" ] || OUT="$OUT/CONTRIBUTING.md"
            shift
            ;;
        *)
            log ERROR "Unrecognized option $1."
            ;;
    esac
    shift
done
[ -n "$OUT" ] || log ERROR "No output provided. See help information."
[ -n "$COPYRIGHT" ] || COPYRIGHT="$DEFAULT_COPYRIGHT"

# Check tool's depedencies
for tool in $TOOL_DEPS; do
    command -v "$tool" >/dev/null 2>&1 || log ERROR "\"$tool\" not found. Make \
sure it is installed on your system and available in PATH. See help \
information."
done

SCRIPT_PATH="$(dirname "$0")"
mkdir -p "$(dirname "$OUT")" || log ERROR "Couldn't create path to $OUT."

log "Converting to markdown..."
pandoc -s --toc --markdown-headings=atx --wrap=none -t gfm \
    --lua-filter="$SCRIPT_PATH/CONTRIBUTING.lua" \
    "$SCRIPT_PATH/../definitions.rst" \
    "$SCRIPT_PATH/gitlab.rst" \
    "$SCRIPT_PATH/reuse.rst" \
    "$SCRIPT_PATH/dco.rst" \
    "$SCRIPT_PATH/project.rst" > "$OUT" || log ERROR "Failed to create the markdown export."

log "Adding REUSE headers..."
reuse addheader --license "$DOCS_LICENSE" --copyright "$COPYRIGHT" \
    --exclude-year "$OUT" || log ERROR "Failed to add REUSE headers."

log "Done. Output available in \"$OUT\"."
