import os,sys,shutil,pexpect
sys.path.insert(0,os.path.abspath("."))
from paver.easy import *
import settings

"""
Pavement file to help with deploying django.
"""

@task
@cmdopts([
	("server=","s","The server to deploy to, this should be a key in the DEPLOYMENTS hash in django settings"),
	("config=","c","The config file to use as the settings.py, (any file in the ./configs/ folder)"),
	("password=","p","The password for the target servers' username, for scp file copying."),
	("quiet","q","Whether or not the scp copy is quiet")
])
def deploy(options):
	"""
	Deploy this project using a deployment option from the settings file.
	Your settings file needs to have a "DEPLOYMENTS" hash available, ex:
	DEPLOYMENTS={
		'slicehost':{
			'ip':'67.23.1.83',
			'user':'admin',
			'dir':'/var/www/vhosts/aaron/cherokee/project/'
		}
	}
	"""
	if not hasattr(options,"server"):
		print "the server parameter is required, run 'paver deploy help'."
		exit()
	if not settings.DEPLOYMENTS.get(options.server):
		print "The server you supplied does not exist in the DEPLOYMENT hash in your settings file."
		print "Not doing anything."
		exit()
	server=settings.DEPLOYMENTS[options.server]
	if not server.get("user",False):
		print "The target server doesn't have a 'user' key."
		print "Not doing anything."
		exit()
	if not server.get("ip",False):
		print "The target server doesn't have an 'ip' key."
		print "Not doing anything."
		exit()
	if not server.get("dir",False):
		print "The target server doesn't have a 'dir' key."
		print "Not doing anything."
		exit()
	if not server.get("password",False) and not hasattr(options,"password"):
		print "The target server doesn't have a 'password' key, and you didn't specify the 'password' switch, I need the password from one or the other."
		print "Not doing anything."
		exit()
	settingfile=os.path.abspath("settings.py")
	tmp_setting=os.path.abspath("settings_tmp.py")
	moved_tmp=False
	if os.path.exists(settingfile):
		moved_tmp=True
		shutil.move(settingfile,tmp_setting)
	preplibapps(options)
	if moved_tmp: shutil.move(tmp_setting,settingfile)
	mvconfig(options)
	if hasattr(options,"quiet"): child=pexpect.spawn('scp -r -q '+os.path.abspath(".")+' '+server.get("user")+"@"+server.get("ip")+":"+server.get("dir"))
	else: child=pexpect.spawn('scp -r '+thispath+' '+server.get("user")+"@"+server.get("ip")+":"+server.get("dir"))
	child.expect('.ssword:*')
	child.sendline(options.password)
	child.interact()

@task
@cmdopts([
	("config=","c","The config file to use as the settings.py, (any file in the ./configs/ folder)")
])
def mvconfig(options):
	"""copy a saved config file from configs/ to settings.py"""
	if not hasattr(options,"config"):
		print "The config parameter is required, run 'paver help deploy'"
		print "Not doing anything."
		exit()
	setting=os.path.abspath("./configs/"+options.config+".py")
	if not os.path.exists(setting):
		print "The file "+setting+" doesn't exist"
		print "Not doing anything."
		exit()
	copyto=os.path.abspath("settings.py")
	print "copying file "+setting+" to "+copyto
	shutil.copy(setting,copyto)

@task
def preplibapps():
	"""
	Move lib apps into libs folder. Your settings file should have a LIB_APPS tuple available. EX:
	--
	LIB_APPS=(
		'dilla',
		'antaresia',
		'debug_toolbar',
	)
	INSTALLED_APPS=(...)
	INSTALLED_APPS+=LIB_APPS
	--
	Every library app needs to be discoverable in your python path.
	"""
	if not hasattr(settings,"LIB_APPS"):
		print "your settings module needs to have a LIB_APPS tuple, it wasn't found."	
		exit()
	lib_apps=settings.LIB_APPS
	paths=sys.path
	found_apps={}
	libappsdir=os.path.abspath("libs")
	if os.path.exists(libappsdir): shutil.rmtree(libappsdir)
	for path in paths:
		for app in lib_apps:
			if found_apps.get(app,None): continue
			apppath=os.path.abspath(path+"/"+(app.replace(".","/"))+"/")
			if os.path.exists(apppath):
				found_apps[app]=True
				shutil.copytree(apppath,("./libs/"+app+"/"))
	for app in lib_apps:
		if not found_apps.get(app,None):
			print "App "+app+" was not found, and cannot be copied into the vedor/apps directory. Make sure it's in your python path."
	os.system("touch ./libs/__init__.py")

@task
@cmdopts([
	("config=","c","The new name of the config file (without .py), which get's stored in configs/")
])
def savesettingsas(options):
	"""Save the current settings.py file as another config file in the configs/ directory."""
	if not hasattr(options,"config"):
		print "The config switch is required, run paver help savesettingsas for more info."
		print "Not doing anything."
		exit()
	setting=os.path.abspath("settings.py")
	dest=os.path.abspath("./configs/"+options.config+".py")
	if not os.path.exists(setting):
		print "settings.py doesn't exist, not doing anything."
		exit()
	shutil.copy(setting,dest)