#!/bin/bash
#
# Note: export cookies.txt to the same folder 
#       containing the current script. 
# 
# CMD: $0 {url}
#      where {url} is the authenticate url 
#      generated by OAuth utilities
# 
# OUTPUT: 
#     1. stdout
#     2. $tmp/autho.code
# (You can configure the channel get_code command
# to be "(default)", and copy the code from console
# manually to your snsapi running console)
# 
# Pre-conditions:
#    * The 'wget' stderr should have '[following]' patterns. 
#      This is how the current script locate the auth'ed url. 
#    * As of this writing, 'http://copy.the.code.to.client/?'
#      is our callback url, which does not redirect to further 
#      places. If this callback url is changed to a real server, 
#      where it redirects after authentication, the current 
#      script may grep out wrong information. (I add 
#      'head -n1' as a fix.)

if [[ $# == 1 ]] ; then
	url=$1
else
	echo "usage:$0 {url}"
	exit 255
fi

fn=`basename $0`
dir=`dirname $0`
tmp="$dir/tmp"
cookies="$dir/cookies.txt"

mkdir -p $tmp
wget --load-cookies $cookies --save-cookies $cookies "$url" -O $tmp/request_url.html > $tmp/request_url.stdout 2> $tmp/request_url.stderr
grep -P '^Location: http:.* \[following\]' $tmp/request_url.stderr | sed -e 's/^Location: //g' -e 's/ \[following\]//g' | head -n1 > $tmp/auth.code
cat $tmp/auth.code

exit 0
