#!/usr/bin/env python
import urllib2
import os

def main():
	number = raw_input('App #: ')
	response = urllib2.urlopen( 'http://appserve.sharefaith.com/appPackage.php?i=' + number )
	CHUNK = 16 * 1024
	with open( number + 'tmp.tgz', 'wb') as f:
		while True:
			chunk = response.read(CHUNK)
			if not chunk:
				break
			f.write(chunk)
	
	OUTDIR = 'output'+number
	if not os.path.exists( OUTDIR ):
		os.mkdir( OUTDIR )
		
	if 0 == os.system( 'tar -zxf ' +number + 'tmp.tgz -C '+OUTDIR ):
		for outdir in os.listdir( OUTDIR ):
			#print os.path.join( OUTDIR, outdir, "data/com.sharefaith.churchapp.prebaked.sqlite" )
			if 0 != os.system("open "+os.path.join( OUTDIR, outdir, "data/com.sharefaith.churchapp.prebaked.sqlite" )):
				os.system("xdg-open "+os.path.join( OUTDIR, outdir, "data/com.sharefaith.churchapp.prebaked.sqlite" ))
	os.system('rm '+ number + 'tmp.tgz')
	
	return 0

if __name__ == '__main__':
	main()

