#!/usr/bin/env python
import subprocess
import optparse
import platform

#-------------------------------------Globals--------------------------------------------------------
install = []
uninstall = ["sudo apt-get remove ruby* ruby*-dev rubygems"]
PLATFORM = platform.system()
ARCHITECTURE = platform.architecture()[0]
	    	
#-------------------------------------Running commands-----------------------------------------------
def run_commands(cmds):
	"""
	Function which run all commands one by one.
	"""
	for cmd in cmds:
		try:
			subprocess.call(cmd, shell=True)
		except Exception as e:
			print e

#----------------------------------------Option parsing----------------------------------------------
def controller():
	"""
	Function to control option parsing.
	"""
	global install, VERBOSE

	#Create instance of OptionParser Module, included in Standard Library
	p = optparse.OptionParser(description='For installing jekyll',
                                            prog='install_jekyll',
                                            version='install_jekyll 0.1',
                                            usage= '%prog [option]')
        p.add_option('--install','-i', action="store_true", help='install jekyll along with ruby.')
        p.add_option('--uninstall','-u', action="store_true", help='uninstall jekyll along with ruby.')
        p.add_option('--verbose', '-v',
                      action = 'store_true',
                      help='prints verbosely',
                      default=False)
                      
        #Option Handling passes correct parameter to runBash
        options, arguments = p.parse_args()
        if options.verbose:
        	VERBOSE=True
        if options.install:
        	if PLATFORM == "Linux":
	    	#----------------------------------------setting commands----------------------------
		        # install build dependencies
                        install.append("sudo apt-get install gcc make software-properties-common python-software-properties")
		    	#Adding repository
			install.append("sudo add-apt-repository ppa:brightbox/ruby-ng")
			#Installing ruby and its gems
			install.append("sudo apt-get update")
			install.append("sudo apt-get install ruby2.2 ruby2.2-dev")
			#Installing jekyll
			install.append("sudo gem install jekyll")
		else:
			print "Wrong operating system detected."

		value = run_commands(install)
	elif options.uninstall:
		value = run_commands(uninstall)
	else:
		p.print_help()

#Runs all the functions
def main():
    controller()

#This idiom means the below code only runs when executed from command line
if __name__ == '__main__':
    main()