#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, shutil

# Opens specified folder, copies all the certificates and important files generated for the app.
# Then you can remove the specified folder, after verifying backup has a copy.

# Choose folder (eg 1.3.0), 1.3.0/number files are copied to backup/number files.

def main():
	if not os.path.exists('backup'):
		os.mkdir('backup')
	
	#Extensions of files to copy:
	IMPORTANTEXT = ['.certSigningRequest', '.p12', '.cer', '.mobileprovision']
		
	folder = raw_input('Which folder? ')
	innerIDs = os.listdir( folder )
	print "backing up:"
	for ext in IMPORTANTEXT:
		print ext
	
	for appID in innerIDs:
		appPath = os.path.join( folder, appID )
		if os.path.isdir( appPath ):
			for name in os.listdir( appPath ):
				#Copy only important file extensions
				for ext in IMPORTANTEXT:
					if name.endswith( ext ):
						output = os.path.join('backup', appID)
						if not os.path.exists( output ):
							os.mkdir( output )
						if not os.path.exists( os.path.join( output, name ) ):
							shutil.copyfile( os.path.join( appPath, name ), 
							                 os.path.join( output, name ) )
				
	return 0

if __name__ == '__main__':
	main()
