#!/usr/bin/env bash

err(){ printf >&2 '[ERROR] %s\n' "$*"; }
info(){ printf >&2 '[INFO] %s\n' "$*"; }

if ! [[ $ZENDESK_TOKEN ]]
then
    err "ZENDESK_TOKEN must be defined in the environment for this script to work"
    exit 1
fi

auth="Authorization: Bearer $ZENDESK_TOKEN"


if (( $# == 0 ))
then
    err 'Provide a filename or directory argument'
    exit 1
fi

declare -a files

for arg
do
    if [[ -d $arg ]]
    then
        files=( "$arg"/*.md )
    else
        files+=( "$arg" )
    fi
done

info "Processing ${files[*]}"

for file in  "${files[@]#./*}"
do
    locale=${file%%/*}
    if ! [[ $locale ]]
    then
        err "Could not determine locale. Skipping $file"
        continue
    fi

    info "Filename $file"

    if ! git diff --quiet "$file"
    then
        err "Please commit before syncing files to the KB"
        git status
        exit 1
    fi

    if ! article_id=$(
        jq -r -e --arg file "${file##*/}" '.[$file]' < article_map.json )
    then
        err "Did not find $file in article map. Skipping."
        continue
    fi

    info "… has article ID $article_id."

    if ! docker run --rm -v "$PWD"/../.markdownlint.yaml:/markdownlint.yaml -i \
        avtodev/markdown-lint:v1 -c /markdownlint.yaml -s < "$file"
    then
        err "File $file failed linting. Skipping."
        continue
    fi

    url="https://pingcap.zendesk.com/api/v2/help_center/articles/$article_id/translations/$locale.json"

    if ! docker run --rm --volume "$PWD:/data" -i pandoc/minimal \
        "$file" -f markdown_github+gfm_auto_identifiers+fenced_code_attributes -o "$file".html
    then
        err "Could not generate HTML for $file. Skipping."
        continue
    fi

    printf '\n<!-- git commit %s -->\n' "$(git rev-parse HEAD)" >> "$file".html

    output=$(
        curl -sS -X GET -H "$auth" "$url" |
            jq --rawfile body "$file".html '.translation.body = $body' |
        curl -sS -X PUT -H "$auth" -H "Content-Type: application/json" -d @- "$url"
    )
    jq 'del(.translation.body)' <<<"$output"

    rm "$file".html
done
