import subprocess
import sys

if len(sys.argv) < 1:
	print "Usage: 'python projectize.py $PROJECT', where $PROJECT is the new project's name"
	sys.exit(0)
else: project_name= sys.argv[1]

if sys.argv[1].endswith("meta"):
	print "It looks like you entered a package name, not a project name."
	print "Please enter the official project name (it should not end with '-meta')"
	print "'-meta' is automatically used in the source ackage's name."

cfg = "./PROJECT"
cmd =["echo '" + project_name + "' > " +cfg]
subprocess.Popen(cmd, shell=True, cwd = "./", stdout=subprocess.PIPE ).communicate()

f_proj = open ("debian/changelog", "r")
current_project_name = f_proj.read()
f_proj.close()
cur_name = current_project_name[:current_project_name.find(" ")]
cur_name_short = cur_name[:cur_name.rfind("-")]

#print "\cur_name: " + cur_name
#print "\cur_name_short: " + cur_name_short
#print "\project: " + project_name
#sys.exit(0)


print "\tOld project name: " + cur_name
print "\tNew project name: " + project_name

cfg = "debian/rules"
cmd =["sed -i 's_" + cur_name_short + "_" + project_name[:len(project_name)] + "_g' " + cfg]
subprocess.Popen(cmd, shell=True, cwd = "./", stdout=subprocess.PIPE ).communicate()
cfg = "debian/control"
cmd =["sed -i 's_PROJECT_" + project_name[:len(project_name)] + "_g' " + cfg]
subprocess.Popen(cmd, shell=True, cwd = "./", stdout=subprocess.PIPE ).communicate()
cfg = "debian/changelog"
cmd =["sed -i 's_" + cur_name_short + "_" + project_name[:len(project_name)] + "_g' " + cfg]
subprocess.Popen(cmd, shell=True, cwd = "./", stdout=subprocess.PIPE ).communicate()

sys.exit(0)
