import sys
import HypercallLib
import struct
import socket
import getopt, traceback



##class guestMType:
##    powerup, powerdown,  = range(1, 4)
##    guestName, guestOs, IPAddresses = range(4, 7)
##    lastSessionMessage, userInfo, newApp, flushApps = range(7, 11)




def buildHcMsg(msg_type, msg):
    msgLength = 16 + len(msg)
    message = ''
    message = struct.pack("IIII",                #format of 4 integers
                      socket.htonl(1),           #channel number (equivalent to HypercallLib.HC_BALLOON)
                      socket.htonl(3),           #Hypercall action 1=register, 2=unregister, 3=forward
                      socket.htonl(msgLength),   #total message length
                      socket.htonl(msg_type)     #vdsm message type see commented class guestMType above  
                      )
    if len(msg) > 0:
        parseString = "%ds"%(len(msg))
        message += struct.pack(parseString, msg[0:])
    return message, msgLength



def run(msg_type, msg):
    streamed_msg, m_len = buildHcMsg(msg_type, msg)
    if HypercallLib.hcInit():
        print "Failed HypercallLib.hcInit()..."
    else:
        if HypercallLib.hcSend(HypercallLib.HC_BALLOON, streamed_msg, m_len):
            print "Failed HypercallLib.hcSend(HypercallLib.HC_BALLOON, '%s', %d)"%(streamed_msg, m_len)
        elif HypercallLib.hcTerm():
            print "Failed HypercallLib.hcTerm()..."
    

def usage():
    print "usage: sendTestHcMsg.py ..."
    print "    -h : prints this help"
    print "    -t : msg type"
    print "         1  - powerup"
    print "         2  - powerdown"
    print "         3  - heartbeat"
    print "         4  - guestName"
    print "         5  - guestOs"
    print "         6  - IPAddresses"
    print "         7  - lastSessionMessage"
    print "         8  - userInfo"
    print "         9  - newApp"
    print "         10 - newApp"
    print "         11 - flushApps"    
    print "    -m : message string"
    

if __name__ == '__main__':
    try:
        additional_err_msg = ''
        msg = ''
        msg_type = 3
        opts, args = getopt.getopt(sys.argv[1:], "hm:t:", ["help"])
        for o,v in opts:
            o = o.lower()
            if o == "-h" or o == "--help":
                raise Exception
            if o == "-t":
                msg_type = int(v);
            if o == "-m":
                msg = v
    except:
        if additional_err_msg != '':
            print additional_err_msg
            print "          "
        usage()
        sys.exit(-1)
    try:
        run(msg_type, msg)
    except:
        traceback.print_exc()
