#!/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

if ! read -r section < section.id
then
    err "Could not read section ID from section.id"
    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 "File $file is already in article map as $article_id. Skipping."
        continue
    fi

    info "… is not yet in article_map.json."

    url="https://pingcap.zendesk.com/api/v2/help_center/sections/$section/articles.json"

    # https://pingcap.zendesk.com/api/v2/help_center/user_segments.json
    #    360001668034 is "staff". Article will only be visible to "staff" when created.
    # https://pingcap.zendesk.com/api/v2/guide/permission_groups.json
    #    3552134 is "managers". Article can only be updated by "managers" when created.

    article_json='{
      "article": {
	"title": "",
	"body": "",
	"locale": "",
	"user_segment_id": 360001668034,
	"permission_group_id": 3552134
      },
      "notify_subscribers": false
    }'

    if ! title=$( grep '^# ' "$file" )
    then
        err "Could not get title from $file. Skipping."
        continue
    fi
    title="${title#* }" # Remove leading "# " from article title

    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 transform MD to HTML. Aborting."
        exit 1
    fi


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

    if ! article_add_output=$(
        curl -sS -X POST -H "$auth" -H "Content-Type: application/json" -d @<(
            jq --rawfile body "$file".html \
                --arg title "$title" \
                --arg locale "$locale" \
                '.article.body = $body | .article.title = $title | .article.locale = $locale' \
                <<<"$article_json"
        ) "$url" ) || jq_error=$(jq -e .error <<<"$article_add_output")
    then
        err "Failed to add article. Aborting."
        [[ $jq_error ]] && err "jq error: $jq_error"
        exit 1
    fi

    if ! article_id=$( jq .article.id <<<"$article_add_output" )
    then
        err "Could not get article.id. Aborting."
        err "NOTE! Article was added but its ID could not be determined!"
        exit 1
    fi

    if ! article_map=$(< article_map.json)
    then
        err "Could not load article_map.json. Aborting."
        err "NOTE! Article was added as $article_id but map not updated!"
        exit 1
    fi

    if ! new_article_map=$(
        jq --arg file "${file##*/}" --arg article_id "$article_id" \
            '.[$file] = ($article_id | tonumber)' <<<"$article_map"
    )
    then
        err "Could not update article map. Aborting."
        err "NOTE! Article was added as $article_id but map not updated!"
        exit 1
    fi
    
    if ! printf '%s\n' "$new_article_map" > new_article_map.json
    then
        err "Could not write new article map. Aborting."
        err "New map: $new_article_map"
        exit 1
    fi

    if ! mv new_article_map.json article_map.json
    then
        err "Could not write new article map. Aborting."
        err "NOTE! Article map may have been cloberred!"
        err "Old map: $article_map"
        err "New map: $new_article_map"
        exit 1
    fi

    info "Article added as $article_id!"
    jq 'del(.article.body)' <<<"$article_add_output"

    rm "$file".html
done
