#!/usr/bin/env python

import sys, os, os.path

def error(message, code):
    print >>sys.stderr, message
    exit(code)

if len(sys.argv) != 2:
    error("Usage: remove-php-end-tags path", 2)

path = sys.argv[1]

if not os.path.exists(path):
    error("Path does not exist: %s" % path, 3)

def process_file(path):
    with open(path) as f:
        content = f.read()
    if content.endswith('?>'):
        content = content[:-2].strip() + "\n"
        with open(path, 'w') as f:
            f.write(content)

def process_dir(path):
    for root, dirs, files in os.walk(path):
        if '.svn' in dirs:
            dirs.remove('.svn')
        for file in files:
            if file.endswith('.php'):
                path = os.path.join(root, file)
                process_file(path)

if os.path.isdir(path):
    process_dir(path)
else:
    process_file(path)
