#! /usr/bin/make -f 

version:=$(shell date +%Y%m%d)

ftp:=ftp://ftp2.census.gov/geo/tiger/TIGER2007FE/

# My database
db:=quinn
P:=psql -d ${db}
# My schema, use public for default
S:=census
# My inputer
s2p:=shp2pgsql -s 4269 -d -I 


# My preferred SRID
srid:=3310

# My States
state:='CA'

# Generic FTP Getting tool
define census_get
	[[ -f $1.zip ]] || wget ${ftp}/$1.zip -O $1.zip
	(cd CaSIL; unzip $1.zip)
endef

define census_to_pgsql
.PHONY: $2
$2: $2.pg
${2}.pg: $(patsubst %,$1.%,shp dbf shp.xml shx prj)
$(patsubst %,$1.%,shp dbf shp.xml shx prj):
	$(call census_get,${states_src})

$2.pg: 
	${s2p} $1.shp $S.$2 | $P > /dev/null
	echo $S.$2 from $1 >  $2.pg

endef

info:
	@echo use make zip for zipcodes for CA in Teale Albers.

.PHONY: schema
schema: schema.pg
schema.pg:
	if [[ -z `$P -t -A -c '\dn $S'` ]]; then \
	  $P -c 'create schema $S' > $@; \
	else \
	  echo 'Exists' > $@; \
	fi;

# We will assume you have no method of gettign your state but the
# CENSUS, this makes it at least self-consistant, if not perfectly
# accurate.
states_src:=fe_2007_us_state
$(eval $(call census_to_pgsql,${states_src},states))


# Zipcode information at ttp://www.census.gov/geo/www/tiger/tigermap.html#ZIP
zipcode_src := fe_2007_us_zcta500
$(eval $(call census_to_pgsql,${zipcode_src},zipcode_us))

zipcode.pg: zipcode_us.pg
	$P -c "set search_path=$S,public; \
	drop table if exists $S.zipcode; \
	create table $S.zipcode as \
	  select zcta5ce00 as zipcode, z.the_geom from zipcode_us z, states s \
	  where s.stusps='CA' and intersects(s.the_geom,z.the_geom); \
	alter table zipcode add column zip5 integer; \
	update zipcode set zip5=zipcode::int where zipcode not like '%X%' and zipcode not like '%H%'; \
	select AddGeometryColumn('$S','zipcode','bound',${srid},'MULTIPOLYGON',2); \
	update $S.zipcode set bound=transform(the_geom,${srid});\
	"
	echo "zipcode ...Modified" > $@

$(patsubst %,zipcode.%,shp dbf shx): zipcode.pg
	pgsql2shp -g bound -f zipcode.shp ${db} $S.zipcode

zipcode.shp.xml: zipcode.shp CaSIL/zipcode_tmpl.xml
	merge-metadata --template=CaSIL/zipcode_tmpl.xml --data=${zipcode_src}.shp.xml --output=$@ --entity dc.title='California Zipcodes' --entity dc.date=`date --rfc-3339=date`

zipcode.prj:
	$P -t -A -c "select srtext from spatial_ref_sys where srid=${srid}" > $@

.PHONY: zipcode.zip
zipcode.zip: zipcode_${version}.zip

zipcode_${version}.zip: $(patsubst %,zipcode.%, shp dbf shx shp.xml prj)
	zip $@ $+