#!/usr/bin/python

import re
import sys, getopt
from shutil import move
from os import remove, close
from tempfile import mkstemp

def replace(file_path, pattern, subst):
    #Create temp file
    fh, abs_path = mkstemp()
    new_file = open(abs_path,'w')
    old_file = open(file_path)
    for line in old_file:
        new_file.write(line.replace(pattern, subst))
    #close temp file
    new_file.close()
    close(fh)
    old_file.close()
    #Remove original file
    remove(file_path)
    #Move new file
    move(abs_path, file_path)

def main(argv):
    in_installed_apps=None 
    uncomment=None 
    done=None 
    file = ''
    instructions='settings_south_syncdb.py -i <settings.py file> to comment south in installed apps, settings_south_syncdb.py -r -i <settings.py file> to decomment south in installed apps'
    
    try:
       opts, args = getopt.getopt(argv,"hri:",["file="])
    except getopt.GetoptError:
       print 'settings_south_syncdb.py -i <settings.py file>'
       sys.exit(2)
    if not opts:
        print instructions
        sys.exit()
    for opt, arg in opts:
       if opt == '-h':
        print instructions
        sys.exit()
       elif opt == '-r':
         uncomment=True
       elif opt in ("-i", "--file"):
         file = arg
       else:
         print instructions
         sys.exit()
    if uncomment:
        replace(file, '#\'south\',', '\'south\',')
    else:
        replace(file, '\'south\',', '#\'south\',')



                        
                    
if __name__ == "__main__":
   main(sys.argv[1:])