# File Manipulation Class

__author__ = 'sham'

import shutil
import logging

def SedFile(filename, search_s, replace_s, unicode_conv=True):
  ''' Updates a file on disk by replacing the search_s with replace_s

  Args:
    filename: the name of the file to read
    search_s: the string to search for
    replace_s: the string to replace with
    unicode_conv: should search_s and replace_s be converted to unicode
  
  Returns:
    True if it worked, False otherwise

  '''
  try:
    shutil.copyfile(filename, filename + ".bak")
  except IOError:
    print "couldn't backup file"
    pass
  
  try:
    newfilecontents = GetUpdatedFileContents(filename, search_s, replace_s, unicode_conv)
    f = open(filename, "wb")
    f.truncate(0)
    f.seek(0)
    f.write(newfilecontents)
  except IOError:
    return False
  
  if f:
    f.close()
  return True

def GetUpdatedFileContents(filename, search_s, replace_s, unicode_conv=True):
  ''' Reads in a file, searches content for the first instance of search_s and replaces with replace_s, returns the updated
      Note this doesn't modify the file on disk
      
  Args:
    filename: the name of the file to read
    search_s: the string to search for
    replace_s: the string to replace with
    unicode_conv: should search_s and replace_s be converted to unicode
  
  Returns:
    A string containing the file contents of the updated file
  
  '''
  
  try:
    f = open(filename, "rb")
    data = f.read()
    logging.debug ("data len: %s, search: %s, replace %s" % (len(data), search_s, replace_s))
    if unicode_conv:
      search_s = unicodify(search_s)
      replace_s = unicodify(replace_s)
    if len(replace_s) < len(search_s):
      padlength = len(search_s) - len(replace_s)
      replace_s += "\x00" * padlength
    else:
      replace_s = replace_s[0:len(search_s)]
      
    foo = data.find(search_s)
    logging.debug("lengths: %s %s" % (len(search_s), len(replace_s)))
    logging.debug("found at %s" % foo)
    data = data.replace(search_s, replace_s, 1)
  except IOError:
    return None
  
  if f:
    f.close()
  return data



def unicodify(input):
  output = ""
  for char in input:
    output += char + "\x00"
  return output

#print SearchAndReplace(r"c:\test\batrun.exe", "test", "woot")
#print SearchAndReplace(r"c:\test\batrun.exe", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", 
#                       '"' + r"c:\Documents and Settings\Administrator\Local Settings\Temp\commands.bat" + '"')

