#!/usr/bin/python3

import asyncio
import os
import sys

from_git = False
git_path = None
f_path = os.path.dirname(os.path.realpath(__file__))
proj_path = os.path.normpath(os.path.join(f_path, "../.git"))
mod_path = None
if os.path.isdir(proj_path):
	base_path = os.path.normpath(os.path.join(proj_path, "../"))
	mod_path = os.path.join(base_path, "funtoo_ramdisk")
	support_path = os.path.join(mod_path, "support")
	if not os.path.exists(mod_path):
		raise FileNotFoundError(f"from_git: Did not find {mod_path} where I expected to find it.")
	if not os.path.exists(support_path):
		raise FileNotFoundError(f"from_git: Did not find {support_path} where I expected to find it.")
	from_git = True
	sys.path.insert(0, base_path)
	support_root = os.path.join(mod_path, "support")
	git_path = proj_path

if not from_git:
	# import the module just to use it to get the path to the files.
	import funtoo_ramdisk
	support_root = os.path.normpath(os.path.join(funtoo_ramdisk.__file__, "../support"))

from funtoo_ramdisk.initramfs import InitialRamDisk
from funtoo_ramdisk.version import __version__
from funtoo_ramdisk.const import RamDiskArguments
from funtoo_ramdisk.args import Arguments
from funtoo_ramdisk.log import get_logger
log = get_logger()


if from_git:
	__version__ += "+git"


async def main_thread(args: Arguments):
	ramdisk = InitialRamDisk(
		args=args,
		support_root=support_root,
		pypath=mod_path,
	)
	return ramdisk.run()


if __name__ == "__main__":
	args = RamDiskArguments(app="funtoo-ramdisk", version=__version__, from_git=from_git, git_path=git_path)
	# Get optional args, and actions/unknown args in extra_args:
	try:
		args.parse()
		success = asyncio.run(main_thread(args))
	except Exception as e:
		log.error(f"{e.__class__.__name__}: {e}")
		if args.values and args.values.backtrace:
			log.print_exception(show_locals=False)
		success = False
	if not success:
		sys.exit(1)
