'''
Created on Jun 14, 2010

@modified: Jun 14, 2010
@author: Dale Hamel
@contact: umhameld@cc.umanitoba.ca
'''

import os
import sys
import shutil
import tarfile
import urllib2



PROGRAM = "getbirch.py: "


class GetBirch:
	
	def __init__(self, mode="test"):
		
		self.mode = mode
		self.temp_dir = os.getcwd() + "/temp"
		self.svn_repo = "http://birchscripts.svn.sourceforge.net/viewvc/birchscripts.tar.gz?view=tar"

	def get_phase2(self):

		print(PROGRAM + "Getting phase2...")
		
		if (not os.path.exists(self.temp_dir)):
			os.mkdir(self.temp_dir)
			
		os.chdir(self.temp_dir)
		curr_dir = os.getcwd()
		
		tarball = urllib2.urlopen(self.svn_repo)
		output = open('getbirch.tar.gz', 'wb')
		output.write(tarball.read())
		output.close()
		
		#os.system("curl -o getbirch.tar.gz ")
		
		if(os.path.exists(curr_dir + "/getbirch.tar.gz")):
			return True
		else:
			return False

	def setup_phase2(self):
		
		curr_dir = os.getcwd()
		print(PROGRAM + "Extracting phase2 to: " + curr_dir)
		
		
		tarball = tarfile.open("getbirch.tar.gz")
		tarball.extractall()
		tarball.close()


		if(os.path.exists(curr_dir + "/birchscripts/getbirch")):
			getbirch_dir = os.getcwd() + "/birchscripts/getbirch"
			os.chdir(getbirch_dir)
			sys.path.append(getbirch_dir)
			sys.path.append(curr_dir + "/birchscripts")	
			return True

		else:
			print(PROGRAM + "Failed to extract archive")
			return False
	
	def exec_phase2(self):
		print(PROGRAM + "Executing phase2")
		from getbirchphase2 import install_birch
		install_birch()
		
	def cleanup(self):
		
		if (os.path.exists(self.temp_dir)):
			print(PROGRAM + "Removing temporary files...")
			shutil.rmtree(self.temp_dir)
			

def main():
	
	mode = "test"
	if ("run" in sys.argv):
		mode = "run"
	
	fetcher = GetBirch(mode)
	
	if (fetcher.mode == "run"):
		fetcher.get_phase2()
		fetcher.setup_phase2()
		fetcher.exec_phase2()
		fetcher.cleanup()
	
	print(PROGRAM + "Completed execution normally")

if ("-test" in sys.argv):
    pass
else:
    main()
