import __main__
import argparse
import os
import re
import stat

from subprocess import Popen, PIPE, STDOUT

# helper functions to run terminal commands
def sh(cmd, dry_run = False, print2stdout = True):
	if dry_run : 	# if this is a dry_run, only print the commands that would be ran
		print("cmd: %s" % cmd)
		return 0, None
	else :			# otherwise create a pipe and run the desired command
		proc = Popen(cmd, stdout=None if print2stdout else PIPE, stderr=STDOUT, shell=True)
		out, err = proc.communicate()
		return proc.returncode, out

# Remove 1 or more files silently
def rm( files, dry_run = False ):
	try:
		for file in files:
			sh("rm -f %s > /dev/null 2>&1" % file, dry_run)
	except TypeError:
		sh("rm -f %s > /dev/null 2>&1" % files, dry_run)

def chdir( dest = __main__.__file__ ):
	abspath = os.path.abspath(dest)
	dname = os.path.dirname(abspath)
	os.chdir(dname)

# helper function to replace patterns in a file
def file_replace(fname, pat, s_after):
    # first, see if the pattern is even in the file.
    with open(fname) as f:
        if not any(re.search(pat, line) for line in f):
            return # pattern does not occur in file so we are done.

    # pattern is in the file, so perform replace operation.
    with open(fname) as f:
        out_fname = fname + ".tmp"
        out = open(out_fname, "w")
        for line in f:
            out.write(re.sub(pat, s_after, line))
        out.close()
        os.rename(out_fname, fname)

# helper function to check if a files contains only a spacific string
def fileContainsOnly(file, text) :
	with open(file) as f:
		ff = f.read().strip()
		result = ff == text.strip()

		return result;

# check whether or not a file is executable
def fileIsExecutable(file) :
	try :
		fileinfo = os.stat(file)
		return bool(fileinfo.st_mode & stat.S_IXUSR)
	except Exception as inst:
		print(type(inst))    # the exception instance
		print(inst.args)     # arguments stored in .args
		print(inst)
		return False

# check if arguments is yes or no
def yes_no(string):
	if string == "yes" :
		return True
	if string == "no" :
		return False
	raise argparse.ArgumentTypeError(msg)
	return False

# diff two files
def diff( lhs, rhs, dry_run ):
	# diff the output of the files
	diff_cmd = ("diff --ignore-all-space "
				"--ignore-blank-lines "
				"--old-group-format='\t\tmissing lines :\n"
				"%%<' \\\n"
				"--new-group-format='\t\tnew lines :\n"
				"%%>' \\\n"
				"--unchanged-group-format='%%=' \\"
				"--changed-group-format='\t\texpected :\n"
				"%%<"
				"\t\tgot :\n"
				"%%>\n' \\\n"
				"--new-line-format='\t\t%%dn\t%%L' \\\n"
				"--old-line-format='\t\t%%dn\t%%L' \\\n"
				"--unchanged-line-format='' \\\n"
				"%s %s")

	# fetch return code and error from the diff command
	return sh(diff_cmd % (lhs, rhs), dry_run, False)