#!/usr/bin/env bash

set -e

command:scopes() {
  get-args token_id
  basic-auth
  api-get "/authorizations/$token_id"
}

ok:scopes() {
  local i=0 scopes scope
  while true; do
    scope="$(JSON.get -s "/scopes/$i" - 2>/dev/null || echo '')"
    [ -z "$scope" ] && break
    scopes+=("$scope")
    let i=i+1
  done

  if "$raw_output" || "$quiet_output"; then
    for scope in "${scopes[@]}"; do
      out "$scope"
    done
    return
  fi

  out
  out "The current scopes for token-id:$token_id are:"
  if [ ${#scopes[@]} -eq 0 ]; then
    out --None--
  else
    for scope in "${scopes[@]}"; do
      out "- $scope"
    done
  fi
  cat <<eos

Available scopes are:
  user          Read/write access to profile info only.
  user:email    Read access to a user’s email addresses.
  user:follow   Access to follow or unfollow other users.
  public_repo   Read/write access to public repos and organizations.
  repo          Read/write access to public and private repos and orgs.
  repo:status   Read/write access to public and private repo commit statuses.
  delete_repo   Delete access to adminable repositories.
  notifications Read access to a user’s notifications.
  gist          Write access to gists.

For more info, see: http://developer.github.com/v3/oauth/#scopes
eos
}

all_scopes=(
  user user:email user:follow
  public_repo repo repo:status delete_repo
  notifications gist
)
command:scope-add() {
  scopes=("${all_scopes[@]}")
  if "$do_all"; then
    get-args token_id
  else
    get-args token_id @scopes
  fi
  check-token-id "$token_id"
  basic-auth
  local array="$(json-dump-array ${scopes[*]})"
  local json="$(json-dump-object add_scopes "$array")"
  api-patch "/authorizations/$token_id" "$json"
  msg_ok="Scopes added: ${scopes[*]}"
}

command:scope-remove() {
  scopes=("${all_scopes[@]}")
  if "$do_all"; then
    get-args token_id
  else
    get-args token_id @scopes
  fi
  basic-auth
  local array="$(json-dump-array ${scopes[*]})"
  local json="$(json-dump-object remove_scopes "$array")"
  api-patch "/authorizations/$token_id" "$json"
  msg_ok="Scopes removed: ${scopes[*]}"
}

# vim: set lisp:
