#!/usr/bin/env python3

import sys
WEBSITE = "https://notabug.org/GPast/$NAME/"

def build_dlmod(tag, vrs):
	LINES = ["## $TAG$VRS", "* [Debian Package]("+WEBSITE+"raw/archive/$VRS/$NAME\-$VRS.deb)", \
	"* [Source Code (tar.gz)]("+WEBSITE+"raw/archive/$VRS/$NAME\-$VRS.tar.gz)", ""]
	return "\n\n".join(LINES).replace("$VRS", vrs).replace("$TAG", tag)

def build_dlpage(name):
	with open("../Wiki/versions.txt", mode="r") as f:
		vrs = f.read().splitlines()
	
	PAGE = "Welcome to the $NAME downloads page! The latest version is **"+vrs[0].split("\t")[1]+\
	"**, and we recommend you use this.\nFor information on installation, please see the [User Documentation]("+\
	WEBSITE+"wiki/User+Documentation).\n\n"
	for line in vrs:
		if line == "":
			continue
		segs = line.split("\t", maxsplit=1)
		PAGE += build_dlmod(*segs)

	PAGE += "## [ALL RELEASES]("+WEBSITE+"src/archive/)"
	
	with open("../Wiki/Downloads.md", mode="w") as f:
		f.write(PAGE.replace("$NAME", name))
	return 0


def srs_update(vrs):
	with open("../Wiki/versions.txt", mode="r") as f:
		vrsPub = f.read()
	
	srs = vrs.rsplit(".", maxsplit=1)[0]+"."
	segs = vrsPub.split(srs, maxsplit=1)
	if len(segs) != 2:
		if len(segs) == 1:
			print("Error: series for %s not found in releases." % vrs)
		else:
			print("Error: series for %s appears to be duplicated." % vrs)
		sys.exit(3)
	segsone = segs[1].split("\n", maxsplit=1)
	
	with open("../Wiki/versions.txt", mode="w") as f:
		f.write(segs[0]+vrs+"\n"+segsone[1])
	return 1
	
def srs_make(vrs):
	with open("../Wiki/versions.txt", mode="r") as f:
		vrsPub = f.read()
	with open("../Wiki/versions.txt", mode="w") as f:
		f.write("LATEST\\- \t%s\n" % vrs)
		f.write(vrsPub.replace("LATEST\\- ", ""))
	return 1

def srs_dep(srs):
	with open("../Wiki/versions.txt", mode="r") as f:
		vrsPub = f.read().splitlines()
	
	vrs = ""
	for line in vrsPub:
		if not srs+"." in line:
			vrs += line+"\n"
	
	with open("../Wiki/versions.txt", mode="w") as f:
		f.write(vrs)
	return 1
	
def sites_update(name):
	with open(name+"/docs/supportedsites.md", mode="r") as f:
		sites = f.read().splitlines()[1:]
	with open("../Wiki/Supported Sites.md", mode="w") as f:
		f.write("The following sites, listed alphabetically, are supported by the latest release of %s:\n\n" % name)
		f.write("\n".join(sites))


FUNCS = {"dlpage": (build_dlpage, 1), "series-update": (srs_update, 1), "series-make": (srs_make, 1), "series-dep": (srs_dep, 1), "sites-update": (sites_update, 1)}
args = sys.argv[1:]
while len(args) != 0:
	cmd = args.pop(0)[2:]
	cmd, argcnt = FUNCS[cmd]
	argset = args[:argcnt]
	args = args[argcnt:]
	cmd(*argset)