#!/usr/bin/env python3

"""
@file     cursely_push_config
@date     26/06/2023
@author   Julio Cabria
"""

import os
import shutil
import subprocess
import sys
from contextlib import suppress
from time import time

HOME_DIR = os.path.expanduser("~")
TMP_DIR = os.path.join(HOME_DIR, "tmp")
GIT_DIR = os.path.join(TMP_DIR, f"cursely_git_{int(time())}")
AUX_DIR = os.path.join(TMP_DIR, "cursely_git_aux")
CONFIG_DIR = ""
if sys.platform == "linux":
    MINECRAFT_DIR = os.path.join(HOME_DIR, ".minecraft")
elif sys.platform == "win32":
    MINECRAFT_DIR = os.path.join(HOME_DIR, "AppData", "Roaming", ".minecraft")


# Check input arguments
if len(sys.argv) == 1:
    print("\nUsage: cursely_push_config.py <modpack_name>\n")
    sys.exit(1)
MODPACK_NAME = sys.argv[1]
CONFIG_DIR = os.path.join(AUX_DIR, f"{MODPACK_NAME}_config")

# Recreate the temporal folder
shutil.rmtree(TMP_DIR, ignore_errors=True)
os.makedirs(TMP_DIR, exist_ok=True)

# Clone the julynx/cursely repo to /tmp/cursely_git
print("\nCloning julynx/cursely repo to /tmp/cursely_git...")
subprocess.run(["git", "clone", "https://github.com/Julynx/cursely", GIT_DIR],
               stdout=subprocess.DEVNULL,
               stderr=subprocess.DEVNULL)
print("Done!\n")

# Create modpack config folder and copy necessary files
print("Packaging modpack config...")
os.makedirs(CONFIG_DIR, exist_ok=True)

shutil.copytree(os.path.join(MINECRAFT_DIR, "config"),
                os.path.join(CONFIG_DIR, "config"), dirs_exist_ok=True)

shutil.copytree(os.path.join(MINECRAFT_DIR, "defaultconfigs"),
                os.path.join(CONFIG_DIR, "defaultconfigs"), dirs_exist_ok=True)

shutil.copytree(os.path.join(MINECRAFT_DIR, "resourcepacks"),
                os.path.join(CONFIG_DIR, "resourcepacks"), dirs_exist_ok=True)

shutil.copytree(os.path.join(MINECRAFT_DIR, "shaderpacks"),
                os.path.join(CONFIG_DIR, "shaderpacks"), dirs_exist_ok=True)

with suppress(FileNotFoundError):
    shutil.copy2(os.path.join(MINECRAFT_DIR, "options.txt"),
                 os.path.join(CONFIG_DIR, "options.txt"))

with suppress(FileNotFoundError):
    shutil.copy2(os.path.join(MINECRAFT_DIR, "optionsof.txt"),
                 os.path.join(CONFIG_DIR, "optionsof.txt"))

with suppress(FileNotFoundError):
    shutil.copy2(os.path.join(MINECRAFT_DIR, "optionsshaders.txt"),
                 os.path.join(CONFIG_DIR, "optionsshaders.txt"))

# Zip the modpack config folder
shutil.make_archive(CONFIG_DIR, "zip", AUX_DIR)

# Move modpack config archive to the temporal git folder
shutil.copy2(f"{CONFIG_DIR}.zip", os.path.join(GIT_DIR, "cursely", "modpacks"))
os.chdir(GIT_DIR)
print("Done!\n")

# Add changes, commit, and push
print("Pushing changes to julynx/cursely...")
subprocess.run(["git", "add", "*"])
subprocess.run(["git", "commit", "-m", "Updated modpack config"])
subprocess.run(["git", "push"])
print("Done!\n")

# Clean up
print("Cleaning up...")
shutil.rmtree(TMP_DIR, ignore_errors=True)
print("Done!\n")
