#!/bin/sh

PHPBIN="php -d error_reporting=0 ";

if [ -f "$1" ]; then

	CSV=$(echo $1 | sed s/".txt"/".csv"/g);
	echo -n > $CSV;

	while read f; do

		ADDRESS=$(echo $f)	
		export ADDRESS;

		$PHPBIN << 'EOF' >> $CSV;
<?php
	$address = ucwords(trim(getenv("ADDRESS")));
	
	# Nominatim Usage Policy
	# https://operations.osmfoundation.org/policies/nominatim/
	sleep(1);

	# OpenStreetMap Nominatim API
	$url = 'https://nominatim.openstreetmap.org/search?q=' . urlencode($address) . '&limit=1&format=json';
	$ch = curl_init();
	# Set cURL User Agent
	curl_setopt($ch, CURLOPT_USERAGENT, "PostmanRuntime/7.28.4");	
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_URL, $url);
	$response = curl_exec($ch);
	curl_close($ch);
	
	# Response
	$a = json_decode($response, true);
	echo "\"$address\", ";
	foreach ($a as $array) {
	    foreach ($array as $k => $v) {
	        switch ("$k") {
	            case "lat":
	                echo "$v, ";
	                break; 
	            case "lon":                
	                echo "$v";
	                break;
	        }
	    }
	}


?>
EOF
		echo >> $CSV;
done < $1
# Remove newline character at the end of a file
truncate -s -1 $CSV
else
	echo "Usage: $0 <file>";
fi
