import os, subprocess
home = os.environ["HOME"]
repo = os.path.join(home, ".local", "repo")
try:
	os.mkdir(repo)
except OSError: pass
derp = os.path.join(home, "derp")
if not os.path.exists(derp):
	stuff = os.path.join(home, "creation")
	temp = os.path.join(home, "derptemp")
	subprocess.check_call(["git","clone",stuff,temp])
	subprocess.check_call(["/shared/git-filter-repo", "--force", "--subdirectory-filter", "stories"], cwd=temp)
	os.rename(temp, derp)

i2penv = dict(os.environ)
i2penv["GIT_PROXY_COMMAND"] = os.path.join(home, "code", "i2p", "git", "proxy.sh")
i2penv["GIT_SSH"] = os.path.join(home, "code", "i2p", "git", "ssh.sh")
	
for name in os.listdir(os.curdir):
	if name.endswith("-old"): continue
	if os.path.exists(os.path.join(name, ".git")):
		repodir = os.path.join(repo, name)
		print(repodir)
		if os.path.exists(repodir):
			subprocess.check_call(["git","fetch"],cwd=repodir)
			subprocess.check_call(["git", "fetch", repodir], cwd=os.path.join(derp,name))
			subprocess.call(["git", "add", name], cwd=derp)
			subprocess.call(["git", "commit", "-a", "-S", "-m", "automatic resync while derping"], cwd=derp)
		else:
			subprocess.call(["git", "commit", "-a", "-S", "-m", "automatic stories to repo derp"], cwd=name)
			# these are the source, with no remote in particular
			# origin is just left over from an old bad clone a while ago
			subprocess.call(["git","remote","remove","origin"], cwd=name)
			if not os.path.exists(name+"-old"):
				temp2 = "tempderpugh"
				subprocess.check_call(["git", "clone", name, temp2])
				squelchenv = dict(os.environ)
				# git sucks
				squelchenv['FILTER_BRANCH_SQUELCH_WARNING'] = '1'
				subprocess.check_call(["git", "filter-branch",  "-f",  "--commit-filter",  'git commit-tree -S "$@"', "HEAD"],
															env=squelchenv,
															cwd=temp2)
				subprocess.check_call(["git", "log", "--show-signature"], cwd=temp2)
				print(name)
				if input("OK?").rstrip() != 'yes':
					#shutil.rmtree(temp2
					raise SystemExit(42)
				os.rename(name, name+"-old")
				os.rename(temp2, name)
			subprocess.check_call(["git","clone","--bare",name,repodir])
			subprocess.call(["git", "rm", "-r", name], cwd=derp)
			subprocess.check_call(["git","submodule", "add", "--reference",repodir,
														 "git://cu7pdgl62lmrggtiblz5e5qxydqgmtxnfkaincck755a3noenbla.b32.i2p/"+name,
														 name],
														env=i2penv,
														cwd=derp)
		
