#!/usr/bin/python

import getopt;
import sys;
import os;
import subprocess as sp;
import datetime;
import string


def do_dump_state():
	do_dump_cmd("lsmod", "null", "run");
	do_dump_cmd("dmesg", "null", "run");
	do_dump_cmd("ps", "aux", "run");
	do_dump_cmd("uname", "-a", "run");
	do_dump_cmd("ifconfig", "-a", "run");
	do_dump_cmd("netstat", "-r", "route");
	do_dump_cmd("netstat", "-s", "statistics");
	do_dump_cmd("netstat", "-S", "active_connections");
	do_dump_cmd("df", "-h", "run");
	do_dump_cmd("service", "xsigo status", "xsigo_status");
	do_dump_cmd("lspci", "-xx", "run");
	do_dump_cmd("dmidecode", "null", "run");
	do_dump_cmd("rpm", "-qi orclovn-kernel", "query_info_xsigo-hostdriver");
	do_dump_cmd("rpm", "-qa", "query_all");
	do_dump_cmd("cpuinfo", "proc", "cat");
	do_dump_cmd("devices", "proc", "cat");
	do_dump_cmd("meminfo", "proc", "cat");
	do_dump_cmd("fstab", "etc", "cat");

	do_dump_rootdir("xscore", "/proc/", "driver");
	do_dump_rootdir("xsvnic", "/proc/", "driver");
	do_dump_rootdir("xsvhba", "/proc/", "driver");
	do_dump_rootdir("null", "/proc/", "net");
	do_dump_rootdir("null", "/proc/", "bus");

	do_dump_rootdir("xsigo", "/var/", "log");
	do_dump_rootdir("messages", "/var/", "log");

	do_dump_rootdir("network-scripts", "/etc/", "sysconfig");

	do_dump_rootdir("parameters", "/sys/", "module/xsvnic");
	do_dump_rootdir("parameters", "/sys/", "module/xsvhba");
	do_dump_rootdir("parameters", "/sys/", "module/xscore");
#       Comment it out till OFED 1.5.2 release
#       do_dump_rootdir(fh, "/sys/class/infiniband");

def do_dump_rootdir(param, intf, loc):
	tmp_file = "/tmp/_tmpfile";
	current_path = sp.Popen(["pwd"], stdout = sp.PIPE);
	path = current_path.stdout.read();
	path = path[:-1];

	if intf == "/proc/":
		if param == "null":
			os.system("cp -rf" + " " + intf + loc + "/" + " " + path + intf + loc);
		else:
			if os.path.exists(intf + loc + "/" + param):
				if not os.path.exists(path + intf + loc):
					os.makedirs(path + intf + loc);
				os.system("cp -rf" + " " + intf + loc + "/" + param + " " + path + intf + loc);
	else:
		if os.path.exists(intf + loc + "/" + param):
			if not os.path.exists(path + intf + loc):
				os.makedirs(path + intf + loc);
			os.system("cp -rf" + " " + intf + loc + "/" + param + " " + path + intf + loc);

def do_dump_cmd(cmd, param, opr):
	current_path = sp.Popen(["pwd"], stdout = sp.PIPE);
	path = current_path.stdout.read();
	path = path[:-1];
	tmp_dir = "/tmp/";
	proc_dir = "/proc/";
	etc_dir = "/etc/";

	if opr == "run":
		if param == "null":
			file( path + tmp_dir + cmd, "w+");
			cmd_str = cmd + " >& " + path + tmp_dir + cmd;
			os.system(cmd_str);
		else:
			file(path + tmp_dir + cmd, "w+");
			cmds = cmd + " " + param;
			cmd_str = cmds + " >& " + path + tmp_dir + cmd;
			os.system(cmd_str);
	elif opr == "cat":
		if param == "proc":
			file(path + proc_dir + cmd, "w+");
			cmds = opr + " " +  proc_dir + cmd;
			cmd_str = cmds + " >& " + path + proc_dir + cmd;
			os.system(cmd_str);
		elif param == "etc":
			file(path + etc_dir + cmd, "w+");
			cmds = opr + " " + etc_dir + cmd;
			cmd_str = cmds + " >& " + path + etc_dir + cmd;
			os.system(cmd_str);
	else:
		file(path + tmp_dir + cmd + "_" + opr, "w+");
		cmds = cmd + " " + param;
		cmd_str = cmds + " >& " + path + tmp_dir + cmd + "_" + opr;
		os.system(cmd_str);
        
def do_dump_xen_bugtool():
	cmds = "xen-bugtool" + " " + "--yestoall";
        cmd_str = cmds;
        os.system(cmd_str);
        tar_cmd = "tar -xf /var/opt/xen/bug-report/bug-report*";
        os.system(tar_cmd);
        rm_cmd = "rm -rf /var/opt/xen/"
        os.system(rm_cmd);
        now = datetime.datetime.now()
        date_time = now.strftime("%Y-%m-%d--%H.%M.%S");
        mv_cmd = "mv bug-report*" + " " + "xen-bugtool_logs" + "-" + date_time;
        os.system(mv_cmd);


def do_show_debug():
	xcpm_debug=get_file("/proc/driver/xscore/xcpm/debug");
	vnic_debug=get_file("/proc/driver/xsvnic/debug");
	vhba_debug=get_file("/proc/driver/xsvhba/debug");

	print "Debug levels:";
	print "xcpm:    " + xcpm_debug,;
	print "vnic:    " + vnic_debug,;
	print "vhba:    " + vhba_debug,;
	print;

def do_set_debug(debuglevel):
	if not debuglevel in ("0", "1", "2"):
		print "Invalid debuglevel specified";
		print;
		usage(1);
	print "Setting debuglevel to " + debuglevel;
	set_str = "echo " + debuglevel + " > /proc/driver/xscore/xcpm/debug";
	os.system(set_str);
	set_str = "echo " + debuglevel + " > /proc/driver/xsvnic/debug";
	os.system(set_str);
	set_str = "echo " + debuglevel + " > /proc/driver/xsvhba/debug";
	os.system(set_str);
	print;

def usage(exitstatus):
	print;
	print "Xsigo Linux host config and debug tool";
	print "Possible arguments:";
	print "-d, --showdebug						show current debug loglevels";
	print "-s, --setdebug <0|1|2>					set the debug loglevels";
	print "-o, --outputfile <filename>				optional file name for --dumpstate";
	print "-h, --help						print usage";

	sys.exit(exitstatus);

def get_file(filename):
	try:
		fp = open(filename);
		str = fp.read();
		fp.close();
		return str;
	except:
		return "<not available>";

if __name__ == '__main__':
	print_help=False;
	show_debug=False;
	set_debug=False;
	dump_state=False;

	try:
		optlist, args = getopt.getopt(sys.argv[1:], 'ds:Do:h', 
			[ "showdebug", "setdebug=", "dumpstate", "outputfile=", "--help" ]);
	except getopt.GetoptError:
		usage(1);
	       
	current_path = sp.Popen(["pwd"], stdout = sp.PIPE);
	path = current_path.stdout.read();
	path = path[:-1];
	tmp_dir = "/tmp";
	proc_dir = "/proc";
	etc_dir = "/etc";
	sys_dir = "/sys";
	var_dir = "/var";
	output_file = False;
		
	os.makedirs(path + tmp_dir);
	os.makedirs(path + proc_dir);
	os.makedirs(path + etc_dir);
	os.makedirs(path + sys_dir);
	os.makedirs(path + var_dir);

	file( path + "/" + "version", "w+"); 
	os.system("cat /etc/redhat-release" +  " >& " + path + "/" + "version");

	for option, value in optlist:
		if option in ("-h", "--help"):
			print_help=True;

		if option in ("-d", "--showdebug"):
			show_debug=True;

		if option in ("-s", "--setdebug"):
			set_debug=True;
			debug_level=value;

		if option in ("-o", "--outputfile"):
			output_file=value;
			
	if (print_help):
		usage(0);
	elif (show_debug):
		do_show_debug();
	elif (set_debug):
		do_set_debug(debug_level);
	else:
		do_dump_state();
	if ("XenServer release 5.6" in open('version').read()) or ("XenServer release 6.0" in open('version').read() ):
		do_dump_xen_bugtool();

	now = datetime.datetime.now()
	date_time = now.strftime("%Y-%m-%d--%H.%M.%S");
	host_name = sp.Popen(["uname", "-n"], stdout = sp.PIPE); 
	host_name = host_name.stdout.read()
	host_name = host_name[:-1];
	if (output_file) :
		tar_name = str(output_file)+"-" + host_name + "-" + date_time + ".tar"; 
	else:
		tar_name = "xsigo-support-linux-" + host_name + "-" + date_time + ".tar"; 

	if ("XenServer release 5.6" in open('version').read()) or ("XenServer release 6.0" in open('version').read() ):
		cmd = "tar -cf " + tar_name + " tmp/ proc/ etc/ sys/ var/ xen-bugtool_logs*/";
	else:
		cmd = "tar -cf " + tar_name + " tmp/ proc/ etc/ sys/ var/";
	os.system(cmd);
	
	os.system("rm -rf " + path + tmp_dir);
	os.system("rm -rf " + path + proc_dir);
	os.system("rm -rf " + path + etc_dir);
	os.system("rm -rf " + path + sys_dir);
	os.system("rm -rf " + path + var_dir);

	if ("XenServer release 5.6" in open('version').read()) or ("XenServer release 6.0" in open('version').read() ):
		os.system("rm -rf " + path + "/xen-bugtool_logs*");
		os.system("rm -f " + path + "/" + "version");

# End of file
