#!/usr/bin/env python
#
#vima_control version 0.99
#
#
# Control VIMA VPS Machines from command line
# For registered users of the VPS infrastructure
# https://vima.grnet.gr
#
# Author: Minas Dasygenis, March 2014
#	  http://arch.icte.uowm.gr
#
# License: Creative Commons 3
#



from mechanize import Browser
from getpass import getpass
import sys,signal
from bs4 import BeautifulSoup


firefox = Browser()

def login(user,password):
        # Ignore robots.txt.  Do not do this without thought and consideration.
        firefox.set_handle_robots(False)
        try:
		firefox.open("https://vima.grnet.gr/user/login")
        except:
                print "An Error occured. Connection was forced closed"
                sys.exit(1)
	for i in xrange(0,5):
	 try:
        	firefox.select_form(nr=i)
        	firefox["username"] = user
        	firefox["password"] = password
        	print "Logging in...",i
		try:
                	firefox.submit()
			break
		except:
               		print "HTTP Error 500: Internal Server Error"
                	sys.exit(3)
	 except:
	 	continue


def action(action,machine):
	if action == "status":
		status(machine)
	else:
	#This function does the action on the machine
	#First locate the status
	 status(machine)
	 try:
		firefox.open("https://vima.grnet.gr/cluster/vima2/"+machine+"/"+action);
	 except:
		print "Cannot perform requested action"


def status(machine):
	#This function locates the status of the machine
	try:
		response=firefox.open("https://vima.grnet.gr/cluster/vima2/"+machine+"/poll");
		soup=BeautifulSoup(response)
		stater=soup.find('div', attrs={'id':'instance_status'})
		print "Status:" + stater.text.strip().encode('utf-8')
	except:
		print "Status not available, or something is fishy"


def help():
	print "\nVIMA VPS Control from command line, Dasygenis Minas 2014"
	print "\nUsage %s <username> <password> <machine name> <action>" % (sys.argv[0])
	print "action: shutdown , reboot , startup , status "





if __name__ == '__main__' :

        def handler(*args):
                print "\n\nBye Bye!"
                sys.exit(0)


        signal.signal(signal.SIGINT,handler)

        if len(sys.argv) == 1 :
                user = raw_input("Username: ")
		if user == "" :
			print "Empty String, aborting"
			sys.exit(7)

                passwd = getpass()
		if passwd == "":
			print "Empty String, aborting"
			sys.exit(6)
                login(user,passwd)

                action = raw_input("Action (reboot/startup/shutdown): ")
		if action == "":
			print "Empty String, aborting"
			sys.exit(8)
                machine = raw_input("Machine name: ")
		if action == "":
			print "Empty String, aborting"
			sys.exit(9)
		action(action,machine)
        else :
                if len(sys.argv)==2 and (sys.argv[1] in ["-h","--help"]):
                        help()
                        sys.exit(4)
                elif len(sys.argv) != 5 :
                        print "\nWrong Number of Parameters."
                        help()
                        sys.exit(4)
                else :
                        print "\nInitializing..."
                        login(sys.argv[1],sys.argv[2])
                        action(sys.argv[3],sys.argv[4])




