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

function github-curl() {
	{ set +x; } 2>/dev/null
	
	[[ $# == 0 ]] && set -- "https://api.github.com"
	if [[ -z $githubtoken ]]; then
		! [ -e ~/.githubtoken ] && echo "ERROR: ~/.githubtoken NOT EXISTS" && return 1
		! [ -s ~/.githubtoken ] && echo "ERROR: ~/.githubtoken EMPTY" && return 1
		githubtoken="$(cat ~/.githubtoken)" || return
	fi
	local path="$TMPDIR".github-curl/$$
	[ -f "$path" ] && rm "$path"
	if ! [ -d "$path" ]; then
		mkdir -p "$path" || { ( set -x; mkdir -p "$path" ); return; }
	fi
	if [[ $# != 0 ]] && [[ -n ${!#} ]] && [[ ${!#} != "https://"* ]]; then
		set -- "${@:1:($#-1)}" "https://api.github.com/${!#}"
	fi
	set curl -i -s -S -u $githubtoken:x-oauth-basic "$@"
	"$@"
	# sed '1,/^'$'\r''$/d' # body
	# todo: sed/awk headers
}

[[ $# == 0 ]] || [[ $1 == "--help" ]] && {
	cat <<EOF
usage: github-curl [options] url 
options same as curl options
url - https://api.github.com/<path>
EOF
	exit 0
}

github-curl "$@"
