#!/bin/bash
#
# usage: tig login [-u username[:password]] [-t token] [-s url]
# Authorize with tig and cloud providers

set -e

TIG_ROOT="${TIG_HOME-"$HOME/.tig"}"
TIGRC_PATH="$TIG_ROOT/tigrc"
. "$TIGRC_PATH"

auth_type=""
user_string=""
token=""
tig_link_url="http://tig.link"

usage_short="${BLUE}usage: tig login [-u username[:password]] [-t token] [-s url]"
usage_long="$usage_short\n-u: use basic auth to (re)authorize with github/tig api"
usage_long="$usage_long\n-t: use bearer token authentication to (re)authorize with tig api"
usage_long="$usage_long\n-s: override the tig link url (default: $tig_link_url)${NC}"

usage_short="$usage_short\nuse -h to get supported command information${NC}"

options=":u:t:s:h"
shopt -u nocasematch
OPTIND=1
while getopts "$options" opt ; do
    case "$opt" in
    u )
      auth_type="basic"
      user_string="$OPTARG"
      ;;
    t )
      auth_type="bearer"
      token="$OPTARG"
      ;;
    s )
      tig_link_url="$OPTARG"
      ;;
    h )
      >&2 echo -e "$usage_long" && exit 1
      exit 0
      ;;
    \?)
      >&2 echo -e "Unknown option: -$OPTARG"
      >&2 echo -e "$usage_short"
      exit 1
      ;;
    : )
      >&2 echo -e "Missing option argument for -$OPTARG"
      >&2 echo -e "$usage_short"
      exit 1
      ;;
    * )
      >&2 echo -e "Unimplemented option: -$OPTARG" && exit 1
      >&2 echo -e "$usage_short"
      exit 1
    esac
done
shift $((OPTIND-1))


### --GIT CONFIG--
### Setup global git configuration if not set.

GIT_CONFIG_PATH="$HOME/.gitconfig"
if [ ! -f "$GIT_CONFIG_PATH" ]; then
  >&2 touch "$GIT_CONFIG_PATH"
  >&2 clear
  >&2 echo -e "${CYAN}- setting global git defaults... -${NC}"
fi


user_full_name=""
user_email=""

git_config=$(git config --global -l)

if ! grep -q user.name <<< "$git_config" ; then
  >&2 echo -e "${CYAN}- configuring git friendly user name... -${NC}"
  while [ "$user_full_name" = "" ] ; do
    >&2 echo -n "what is your full name (e.g. 'John Doe')? "
    read user_full_name
    if [ "$user_full_name" = "" ] ; then
      >&2 echo -e "${RED}- that doesn't appear to be a name! try again... -${NC}"
    fi
  done
  >&2 git config --global user.name "$user_full_name"
  >&2 echo -e "${GREEN}- git friendly user name configured as $user_full_name -${NC}"
else
  user_full_name="$(git config --get --global user.name)"
fi

if ! grep -q user.email <<< "$git_config" ; then
  >&2 echo -e "${CYAN}- configuring git email address... -${NC}"
  while [ "$user_email" = "" ] ; do
    >&2 echo -n "what is your email? "
    read user_email
    if [ "$user_email" = "" ] ; then
      >&2 echo -e "${RED}- that doesn't appear to be an email address! try again... -${NC}"
    fi
  done
  >&2 git config --global user.email "$user_email"
  >&2 echo -e "${GREEN}- git email address configured as $user_email -${NC}"
else
  user_email="$(git config --get --global user.email)"
fi


if ! grep -q credential.helper <<< "$git_config" ; then
  if [ "$PNAME" = "windows" ] ; then
    >&2 echo -e "${CYAN}- configuring git credential helper... -${NC}"
    >&2 git config --global credential.helper wincred
    >&2 echo -e "${GREEN}- credential helper configured successfully -${NC}"
  fi
fi

if ! grep -q push.default <<< "$git_config" ; then
  >&2 echo -e "${CYAN}- configuring default git push behavior to simple... -${NC}"
  >&2 git config --global push.default simple
  >&2 echo -e "${GREEN}- git default push behavior configured successfully -${NC}"
fi


if [ "$auth_type" = "basic" ] ; then
  username="$(echo "$user_string" | sed 's/[: ][\w[:punct:] ]+//')"
  password="$(echo "$user_string" | sed 's/[\w[:punct:] ]+://')"

  while [ "$password" = "" ] ; do
    >&2 echo -n "enter your github password: "
    read -s password
    if [ "$password" = "" ] ; then
      >&2 echo -e "${RED}- that doesn't appear to be a valid password! try again... -${NC}"
    fi
  done

  tig_data="{\"full_name\":\"$user_full_name\",\"email\":\"$user_email\",\"hostname\":\"$(hostname)\",\"hostuser\":\"$(id -un)\",\"platform\":\"$PLATFORM\"}"

  tig_credentials="$username:$password"

  tig_response=$(curl -s -u ${tig_credentials} -X POST -d "$tig_data" "$tig_link_url") 2>&1
  echo "$tig_response"
elif [ "$auth_type" = "bearer" ] ; then
  bearer_token_header="Authorization: Bearer $token"
  tig_response="$(curl -s -H "$bearer_token_header" -X POST "$tig_link_url")" 2>&1
  echo "$tig_response"
else
  >&2 echo -e "${RED}- must pass -u or -t flag... -${NC}"
  exit 1
fi

if [ "$renew" = true ] ; then
    >&2 echo "--GitHub credentials are required to interact with the GitHub api--"
    >&2 echo "--Your basic credentials will be exchanged for a token and persisted to ${TIGRC_PATH}--"

    oauth_note="OAuth token for "$(hostname)/$(id -un)"."
    oauth_data="{\"scopes\":[\"repo\",\"write:public_key\"], \"note\":\"$oauth_note\"}"
    oauth_credentials=""
    oauth_credentials_ok=false
    oauth_token_received=false
    oauth_response=""

    while [ "$oauth_token_received" = false ]; do
      if [ "$oauth_credentials_ok" = false ]; then
        ### Read users GitHub credentials
        >&2 echo -n "GitHub Username: "
        read username
        >&2 echo -n "GitHub Password: "
        read -s password
        oauth_credentials="$username:$password"
        >&2 echo -e "\r\n"
      fi

      ### Call GitHub API to get a token.
      oauth_response=$(curl -s -u $oauth_credentials -X POST -d "$oauth_data" https://api.github.com/authorizations) 2>&1

      case "$oauth_response" in
          *"token"*) ### Token Found!
            oauth_credentials_ok=true
            oauth_token_received=true
            >&2 echo "--Token received, persisting to ${TIGRC_PATH}--"
            ;;
          *already_exists*) ### Token already exists but was not found on this machine...
            oauth_credentials_ok=true
            >&2 echo "--Token has already been granted for you but was lost.  Login to window at the right, revoke token named \"$oauth_note\", and close the window--"
            chrome_path="unknown"
            token_url="https://github.com/settings/tokens"
            >&2 chrome "$token_url"
            ;;
          *Bad\ credentials*) ### Wrong username/password provided
            >&2 echo "--The username / password combination you provided was incorrect.  Try again--"
            ;;
          *) ### Unknown Issue
            >&2 echo "--An unknown error occurred.  Log file saved to ${LOG_PATH}--"
            echo "--Unknown issue authenticating with GitHub API - response: $oauth_response--" >> $LOG_PATH
            exit 1
            ;;
      esac
    done

    ### Parse out the token from the json response and stick it in the token file
    echo "$oauth_response" | tr ',' '\n' | tr -d '" {}' | grep ^token: | sed s/token:// | while read token
        do
         if [ ${#token} -eq 40 ]; then
            ### Set the github token in the config
            echo -e "\r\nexport GITHUB_TOKEN=\"$token\"\r\n" >>$TIGRC_PATH
            GITHUB_AUTH_HEADER="Authorization: token $token"
            echo -e "\r\nexport GITHUB_AUTH_HEADER=\"$GITHUB_AUTH_HEADER\"\r\n" >>$TIGRC_PATH
            ### Replace github url with token github url in config
            >&2 sed -bi "s/https:\/\/github.com/https:\/\/$token@github.com/" $TIGRC_PATH

            if [ ! -d "$HOME/.ssh" ]; then
              >&2 echo "--No ssh key found for GitHub, adding now--"
              email=$(git config --get user.email 2>&1)
              >&2 mkdir -p "$HOME/.ssh"
              echo -e "\n\n\n" | ssh-keygen -t rsa -b 4096 -N "" -C "$email" >&2
              ssh_key=$(cat $HOME/.ssh/id_rsa.pub)
              ssh_data="{\"title\": \"$email\",\"key\": \"$ssh_key\"}"

              >&2 curl -X POST -H "Content-type: application/json" -H "$GITHUB_AUTH_HEADER" -d "$ssh_data" "https://api.github.com/user/keys"
              >&2 echo "--SSH key added successfully--"
              >&2 echo "--Adding key to ssh agent--"
              >&2 eval $(ssh-agent -s)
              >&2 ssh-add $HOME/.ssh/id_rsa
              >&2 ssh -oStrictHostKeyChecking=no -T git@github.com
              >&2 echo "--Key added successfully--"
            fi

            update-github-tokens "$token"
         fi
        done
fi

### Source the variable from the config file
#. "$TIGRC_PATH"

#if [ -n "$GITHUB_TOKEN" ]; then
    ### Update all github tokens
    #echo "$GITHUB_TOKEN" | tr -d '\n'
    #exit 0
#else
    #>&2 echo "--GITHUB_TOKEN not found in the config file! Exiting...--"
    #exit 1
#fi
