#!/usr/bin/env python
# SF Plugin packager by Luke Bryan
# Based on SFWebTemplate packager

#Requires slimit module.
# As sudo,
# run pip install slimit.
# In Windows, it's a little tricky, you will need to first install:
# Distribute http://www.lfd.uci.edu/~gohlke/pythonlibs/#distribute
# and pip    http://www.lfd.uci.edu/~gohlke/pythonlibs/#pip
# and run C:\Python27\Scripts\pip.exe install slimit
# and run C:\Python27\Scripts\pip.exe install csscompressor

# In Python2.7.9 just use /c/Python27/Scripts/pip install slimit
# and /c/Python27/Scripts/pip install distribute
# and /c/Python27/Scripts/pip install csscompressor
import slimit

#Fix https://github.com/rspivak/slimit/issues/58
slimit.scope.ID_CHARS='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$'

import shutil, os, sys, subprocess, ftplib
import distutils.archive_util as archive

strt = open('wordpress/plugins/com.sharefaith.churchapp/sf-churchapp.php').read(1024);
sfVersion = strt[strt.find(" Version: ")+10:]
sfVersion = sfVersion[:sfVersion.find('\n')]


SFCP = "//(C) Sharefaith, sharefaith.com. All rights reserved.\n"
# List of (relative path, headercomment)-tuple of all the JS files big enough to benefit from mini-fying.
JS = [
('/js/sf-churchapp-common.js', SFCP),
('/classes/SimSectionActivity/SectionActivityContact.js', SFCP),
('/js/html2canvas.min.js','/*http://html2canvas.hertzen.com */'),
('/js/sf-app-ui.js', SFCP),
('/js/mediaApi.js', SFCP),
('/js/layoutBuilderApp.js', SFCP),
('/js/jquery.placeholder.js',''),
('/js/adminShortcode.js', SFCP),
('/js/apiDroppables.js', SFCP),
('/js/tooltiptour/appPlugin.js', SFCP),
('/js/library/jquery.autoellipsis.js',"""
/*!

    Copyright (c) 2011 Peter van der Spek

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
    
 */
"""),
]
CSS = [
('/css/sf-churchapp-common.css', ''),
('/css/sf-churchapp-simulator.css', ''),
('/css/sf-churchapp-commoncolortheme.css', ''),
('/css/sf-churchapp-jquiStyling.css', ''),
('/css/sf-churchapp-layoutBuilder.css', ''),
('/css/frontend.css', ''),
('/css/mceNotTiny.css', ''),
('/css/wait-spinner.css', '')
]

newFolder = "SFAppPlugin"+sfVersion
print('Will copy to "'+newFolder+'" and zip.')
print("it must not exist.\n\nPress Enter when ready")
try:
	raw_input()
except: #python3
	input()

os.mkdir(newFolder)

print('Copying...')
shutil.copytree('wordpress/plugins/com.sharefaith.churchapp',os.path.join(newFolder,'com.sharefaith.churchapp'))

print("Copied.\n\n")

origTotal = 0
miniTotal = 0
#mydir = os.path.dirname(__file__);
#print mydir
for item in JS:
	raw = open(newFolder+'/com.sharefaith.churchapp'+item[0]).read()
	origTotal += len(raw)#os.stat(newFolder+'/SFWebTemplate'+item[0]).st_size
	minijs = item[1]+slimit.minify(raw, mangle=True)
	
	#Closure compiler will probably be a much more useful choice in the future.
	# - see http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/
	#Advanced optimization probably breaks everything see https://developers.google.com/closure/compiler/docs/api-tutorial3
	#subprocess.call(['compiler/compiler.jar','--compilation_level','ADVANCED_OPTIMIZATIONS','--js','SFWebTemplate'+item[0], '--js_output_file', newFolder+'/SFWebTemplate'+item[0]])
	
	open(newFolder+'/com.sharefaith.churchapp'+item[0],'w').write(minijs)
	miniTotal += len(minijs)#os.stat(newFolder+'/SFWebTemplate'+item[0]).st_size
	print('minified '+newFolder+'/SFWebTemplate'+item[0])

CSSorigTotal = 0
CSSminiTotal = 0
try:
	import csscompressor
	for item in CSS:
		#print os.path.join(mydir,newFolder,'SFWebTemplate',item)
		raw = open(newFolder+'/com.sharefaith.churchapp'+item[0]).read()
		CSSorigTotal += len(raw)
		mini = item[1]+csscompressor.compress(raw)
		
		open(newFolder+'/com.sharefaith.churchapp'+item[0],'w').write(mini)
		CSSminiTotal += len(mini)
		print('minified '+newFolder+'/com.sharefaith.churchapp'+item[0])
	print('minified CSS', CSSorigTotal, 'to', CSSminiTotal)
except ImportError:
	print('No CSScompress module installed, css will not be minified. Please run: sudo easy_install csscompressor')

# Get rid of untracked files in copy before zipping:
#out, err = subprocess.Popen(['git','clean','--dry-run','-d'], stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()
#items = out.split('\n');
#for untracked in items:
	#if untracked.startswith('Would remove ') and untracked.find('com.sharefaith.churchapp/')!=-1:
		##Remove them from the copy:
		#filename = newFolder +'/'+ untracked[13:]
		#print 'Removing untracked', filename
		#if filename.endswith('/'):
			#shutil.rmtree(filename)
		#else:
			#os.remove(filename)
#less/css uncompiled should never be needed in the plugin:
shutil.rmtree( newFolder+'/com.sharefaith.churchapp/css/fa/less' )
shutil.rmtree( newFolder+'/com.sharefaith.churchapp/css/fa/scss' )

#Now is this check necessary anymore?
# For you craaaaazy Mac OS users, we need to remove .DS_Store files.
rootdir = newFolder+'/com.sharefaith.churchapp/'
for root, subFolders, files in os.walk(rootdir):
	#print root, subFolders, files TODO could use files.find to see if is in array:
	outfileName = os.path.join( root, ".DS_Store" )
	if( os.path.isfile( outfileName ) == True):
		os.remove( outfileName )

print("JS Compressed "+str(origTotal)+" to "+str(miniTotal))
from xml.dom.minidom import parse, parseString

if os.path.isfile('ftps.xml'):
	# Create an xml file like so, in ftps.xml:
#<ftps>
  #<site>
    #<host>example.com</host>
    #<user>username</user>
    #<pass>pass</pass>
    #<themedir>directory of wp-content/themes/</themedir>
  #</site>
#</ftps>
	dom = parseString(file('ftps.xml').read())
	sites = dom.getElementsByTagName('site')
	print('Site no. ',range(len(sites)),'?')
	site = raw_input('Enter site number or "zip"')
	if (site != 'zip'):
		for el in sites[site].childNodes:
			#Wow, this is exactly like the JS dom interface
			if (el.nodeType == el.ELEMENT_NODE):
				if (el.tagName == 'user'):
					user = el.childNodes[0].data
				elif el.tagName == 'host':
					host = el.childNodes[0].data
				elif el.tagName == 'pass':
					passwd = el.childNodes[0].data
				elif el.tagName == 'themedir':
					pushdir = el.childNodes[0].data
		if (user and host and passwd and pushdir):
			access = ftplib.FTP(host, user, passwd)
			access.cwd(pushdir) #move to that directory
			try:
				access.mkd('SFWebTemplate')
			except ftplib.error_perm as e:
				print('already exists')
			
			#access.retrlines('LIST')
			#move to SFWebtemplate(version) which has SFWebTemplate to upload:
			os.chdir(newFolder) #now SFWebTemplate is direct folder, makes copy easy:
			copyftpdir('SFWebTemplate', access)
			os.chdir('../')
		else:
			print(""" Unexpected xml """)
	else: #zip
		archive.make_archive(newFolder, 'zip', newFolder)
		print('Zipped package!')

else:
	archive.make_archive(newFolder, 'zip', newFolder)
	print('Zipped package!')

print("Done!")
try:
	if raw_input("clean up? enter or y for yes, n for no:") != 'n':
		shutil.rmtree(newFolder)
except: #python3
	if input("clean up? enter or y for yes, n for no:") != 'n':
		shutil.rmtree(newFolder)