#!/usr/bin/env bash
{ set +x; } 2>/dev/null

usage() {
    echo "usage: $(basename $0) id [description]" 1>&2
    [ "$1" = "-h" ] || [ "$1" = "--help" ]; exit
}

[ "$1" = "-h" ] || [ "$1" = "--help" ] && usage "$@"

[[ $# == 0 ]] && usage

[[ -z "$GITHUB_TOKEN" ]] && echo "ERROR: GITHUB_TOKEN unknown" 1>&2 && exit 1

tmp_output="$(mktemp)" || exit
url="https://api.github.com/gists/$1"
description="${@:2}"
data="{\"description\":\"${description//\"/\\\"}\"}"

http_code="$(
    [[ $# == 1 ]] && set -- || set -- -X PATCH -d "$data"
    set -- "$@" -s -w '%{http_code}' -u "$GITHUB_TOKEN:x-oauth-basic" -o "$tmp_output" "$url"
    curl "$@"
)" || exit
[[ $http_code -ge 300 ]] && { echo "$PWD:" && cat "$tmp_output" ; exit 1; }

[[ $# != 1 ]] && exit
grep '  "description":' "$tmp_output" | head -1 | grep -v ': null,' | rev | cut -c 3- | rev | cut -c 19-
