#!/usr/bin/env python3

# Copyright (C) 2026 Volkov Alexey
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

from alt_workstation_10_11_upgrade.context import AppContext
from alt_workstation_10_11_upgrade.exceptions import (
	RequirementError,
	UpgradeError,
	UserAbort,
)
from alt_workstation_10_11_upgrade.logging_utils import LOG_PATH, setup_logging
from alt_workstation_10_11_upgrade.runner import CommandRunner
from alt_workstation_10_11_upgrade.upgrade import run_upgrade
from alt_workstation_10_11_upgrade.switch import run_switch

import alt_workstation_10_11_upgrade.system as system

import argparse
import os
import logging

def get_parser():
	able_to_switch = system.is_proper_for_switch()
	help_description = "Performs upgrade from P10 to P11"

	if able_to_switch:
		help_description = help_description + " and switch from MATE to GNOME"

	parser = argparse.ArgumentParser(
		description=help_description,
		epilog=f"Log is located in {LOG_PATH}"
	)
	
	parser.set_defaults(switch=False)
	
	parser.add_argument(
		"-v", "--verbose",
		action="store_true",
		help="verbose apt-get output"
	)
	parser.add_argument(
		"-y", "--yes",
		action="store_true",
		help="assume Yes to all queries and do not prompt"
	)
	parser.add_argument(
		"--p11-sources",
		metavar="PATH",
		help="use custom P11 sources.list"
	)
	group = parser.add_argument_group("actions")
	group.add_argument(
		"-u", "--upgrade",
		action="store_true",
		help="perform only upgrade from P10 to P11"
	)
	if able_to_switch:
		group.add_argument(
			"-s", "--switch",
			action="store_true",
			help="perform only switch desktop environment from MATE to GNOME."
		)
	return parser

def print_contact_the_support(stage: str):
	logging.getLogger(__name__).critical(
		"%s failed, contact support to resolve your problem.",
		stage,
	)

def main():
	setup_logging()

	if not os.getuid() == 0:
		logging.getLogger(__name__).critical(
			"The script should be run under root. Aborting."
		)
		exit(1)
	
	logger = logging.getLogger(__name__)

	parser = get_parser()
	args = parser.parse_args()

	try:
		system.ensure_sufficient_space()
	except RequirementError as err:
		logger.critical(str(err))
		exit(1)

	context = AppContext()

	if args.yes:
		context.assume_yes = True

	if args.verbose:
		context.verbose = True

	runner = CommandRunner(ctx=context)

	if args.p11_sources and not os.path.isfile(args.p11_sources):
		logger.critical(
			"Custom P11 sources.list not found: %s\nAborting",
			args.p11_sources
		)
		exit(1)

	if args.upgrade and args.switch:
		logger.info("Upgrading to P11 and switching from MATE to GNOME")
		try:
			run_upgrade(
				runner,
				only_upgrade=False,
				p11_sources=args.p11_sources
			)
			run_switch(runner, is_upgraded=True)
		except UserAbort:
			logger.info("Operation aborted by user.")
			exit(0)
		except UpgradeError:
			exit(1)
		except Exception:
			print_contact_the_support("Upgrade to P11 or switch from Mate to GNOME")
			exit(1)

	elif args.upgrade and not args.switch:
		logger.info("Only upgrading from P10 to P11")
		try:
			run_upgrade(
				runner,
				only_upgrade=True,
				p11_sources=args.p11_sources
			)
		except UserAbort:
			logger.info("Operation aborted by user.")
			exit(0)
		except UpgradeError:
			exit(1)
		except Exception:
			print_contact_the_support("Upgrade to P11")
			exit(1)

	elif args.switch and not args.upgrade:
		logger.info("Only switching from MATE to GNOME")
		try:
			run_switch(runner, is_upgraded=False)
		except UserAbort:
			logger.info("Operation aborted by user.")
			exit(0)
		except UpgradeError:
			exit(1)
		except Exception:
			print_contact_the_support("Switch from Mate to GNOME")
			exit(1)

	else:
		parser.print_help()

if __name__ == "__main__":
	main()
