import os.path
import math
import time
import io
import sys

print("")
print("")
print("Copyright (C) 2023  Samuel \"Reki\" Piper")
print("")
print("This code is free software; you can redistribute it and/or modify")
print("it under the terms of the GNU GPL (General Public License); either")
print("version 2 of the License, or (at your option) any later version.")
print("")
print("")

print("====================================================================================================")
print("|                                                                                                  |")
print("|    &@@@@@@  @@@@@@@, @@@@@@@@@@@@@@@@@  @@@@@@  @@@* @@@@  @@@@@@@@@@@% @@@@@@@@@@@@@@@@@@@@@@   |")
print("|    &@@@@@@@@@@@@@@@,      #@@@@   @@@@  @@@@@@  @@@* %@@@  @@@@                      #@@@@       |")
print("|    &@@@  @@@@  @@@@. @@@@ *@@@@   @@@@  @@@@@@@@@@@* %@@@  @@@@   @@@@% @@@@@  @@@@@ #@@@@       |")
print("|    &@@@  @@@@  @@@@  @@@@  @@@@   @@@@  @@@@@@@@@@@* @@@@  @@@@   ,@@@% @@@@@%%@@@@@ #@@@@       |")
print("|    %@@@  @@@@  @@@@  @@@@  @@@@@@@@@@@  @@@& @@@@@@* #@@@  @@@@@@@@@@@% @@@@@@@@@@@@ (@@@.       |")
print("|    *///  //./  ////  ////  ///(////.     /// #@#((@. ((&@  /@ /&(@@%@%  //%@/  //#/% ,/.  *@@@   |")
print("|                                                                                        (@@@@@@   |")
print("|    @@@@@@@@@@@@@@@@@@@@@  #@@@@@@@     @@@@@@@@   @@@@@@@      @@@@@@@   @@@@@@@@@@@@@@@@@@@@@   |")
print("|    &@@@@@@@@@@@@@@@@@@@@  #@@@@@@@     @@@@@@@@   @@@@@@@@     @@@@@@@   @@@@@@@@@@@@@@@@@@@@/   |")
print("|    &@@@@@@@@@@@@@@@@@@@@  #@@@@@@@     @@@@@@@@   @@@@@@@@@&   @@@@@@@   @@@@@@@@@@@@@@@@@@@@@   |")
print("|    &@@@@@@*               #@@@@@@@    *@@@@@@@@   @@@@@@@@@@@@@@@@@@@@        @@@@@@@(           |")
print("|    &@@@@@@*  /@@@@@@@@@@  #@@@@@@@   %@@@@@@@@@   @@@@@@@@@@@@@@@@@@@@          *@@@@@@#         |")
print("|    &@@@@@@*     @@@@@@@@  #@@@@@@@ #@@@@@@@@@@@   @@@@@@@.@@@@@@@@@@@@            @@@@@@@@@      |")
print("|    &@@@@@@@@@@@@@@@@@@@@  #@@@@@@@@@@@@@@@@@@@@   @@@@@@@   /@@@@@@@@@   @@@@@@@@@@@@@@@@@@@@,   |")
print("|    &@@@@@@@@@@@@@@@@@@@@  #@@@@@@@@@@@@@@@@@@@@   @@@@@@@     %@@@@@@@   @@@@@@@@@@@@@@@@@@@@(   |")
print("|    @@@@@@@@@@@@@@@@@@@@@  #@@@@@@@@@@@@@@@@@@@@   @@@@@@@      @@@@@@@   @@@@@@@@@@@@@@@@@@@@    |")
print("|                                                                                                  |")
print("====================================================================================================")


time.sleep(0.5) # Let the license header display for a bit, so it's not totally missed

print("\n\n")

mapfile_path = ""
base_path = ""
game_path = ""

awaiting = ""
for arg in sys.argv[1:]: # We can skip the first arg, since it's always our script (hack?)
	if awaiting != "":
		if awaiting == "-fs_basepath":
			base_path = arg
		elif awaiting == "-fs_game":
			game_path = arg
		awaiting = ""
	else:
		if arg == "-fs_basepath" or arg == "-fs_game":
			awaiting = arg
		else:
			mapfile_path = arg

print("base_path is " + base_path)
print("game_path is " + game_path)
print("mapfile_path is " + mapfile_path)

if (base_path == "" or game_path == "" or mapfile_path == ""):
	print("invalid path, make sure fs_basepath, fs_game, and map file are specified")
	exit(1)
print("\n")

# parse map file to find mgpfile worldspawn key
mgp_name = ""
if os.path.isfile(mapfile_path):
	f = open(mapfile_path, 'r')
	awaiting_mgpdef = False
	for line in f:
		if line.find("\"classname\"") != -1:
			if awaiting_mgpdef:
				break
			elif line.find("\"worldspawn\"") != -1:
				awaiting_mgpdef = True
		elif line.find("\"mgpfile\"") != -1 and awaiting_mgpdef:
			parts = line.split("\"")
			mgp_name = parts[-2]
			break

	if mgp_name == "":
		mapfile_path.replace("\\", "/")
		map_list = mapfile_path.split("/")
		mgp_name = map_list[-1][:-4]
	f.close()
	

print("mgp_name is " + mgp_name + ".mgp")
# end map parsing


shader_path = base_path + "/" + game_path + "/scripts/temp.shader"
print("shader_path is " + shader_path)


mgp_path =  "scripts/" + mgp_name + ".mgp"

if os.path.isfile(base_path + "/" + game_path + "/" + mgp_path):
	mgp_path = base_path + "/" + game_path + "/" + mgp_path
else:
	for folder in os.listdir(base_path + "/" + game_path):
		if os.path.isdir(base_path + "/" + game_path + "/" + folder) == False: # no files allowed! only folders
			continue
		if folder[-7:] == ".pk3dir":
			if os.path.isfile(base_path + "/" + game_path + "/" + folder + "/" + mgp_path):
				mgp_path = base_path + "/" + game_path + "/" + folder + "/" + mgp_path
				break

print("mgp_path is " + mgp_path)

if os.path.isfile(mgp_path) == False:
	print("mgp file does not exist")
	exit(1)

p = open(mgp_path, 'r')
f = open(shader_path, 'w')

shader_directives = []
texture_names = []

in_batch = False
for line in p:
	cmd = line.strip()
	if cmd == "{":
		in_batch = True
	elif cmd == "}" and in_batch:
		shader_directives.clear()
		texture_names.clear()
		in_batch = False
	elif in_batch == True: # we're reading stuff!
		if cmd[:1] == "$" or cmd[1:] == "#":
			shader_directives.append(cmd[1:])
			print("adding new directive: " + cmd[:1])
		elif len(shader_directives) and len(cmd) > 0:
			print("    adding texture \"" + cmd + "\"")
			texture_names.append(cmd)
			f.write(cmd + "\n")
			f.write("{\n")
			for directive in shader_directives:
				f.write("	" + directive + "\n")
			f.write("	{\n")
			f.write("		map " + cmd + "\n")
			f.write("	}\n")
			f.write("	{\n")
			f.write("		map $lightmap\n")
			f.write("	}\n")
			f.write("}\n")
			f.write("\n")

f.close()
p.close()

exit(0)




