#! /bin/bash

uri_file=$1

LOCAL_DIR="./data"

function find_sameAsses() {
	local viaf_uri=$1
	# download ntriples, filter person class
	local result=`rapper -g $viaf_uri | grep "${viaf_uri}" | grep "http://schema.org/sameAs" | cut -d ' ' -f3 | sed "s/[<>]//g"`
	
	echo "$result"
}



function handle_sameAs_link() {
	
	local sameAsLink=$1

	
	local domain=`awk -F/ '{print $3}' <<<"$sameAsLink"`

	local propfile="${LOCAL_DIR}/${domain}"

	if ! [[ -e $propfile ]];
	then
		touch $propfile
	fi

	rapper -g $sameAsLink | cut -d " " -f2 | sed "s/[<>]//g" >> $propfile
}


cat $uri_file | while read person_uri; do
	# print out a time stamp for debugging
	timestamp=`date +"%D %T"`
	>&2 echo "${timestamp}     ${person_uri}"

	sameAsLinks=$(find_sameAsses $person_uri) 

	>&2 echo "Found sameAs Links: ${sameAsLinks}"

	for sa in $sameAsLinks; do
		
		handle_sameAs_link $sa 
	done
done

