#!/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.logging_utils import setup_logging
from alt_workstation_10_11_upgrade.runner import CommandRunner

from pathlib import Path
import os
import shutil
import sys
from time import sleep

import logging

setup_logging()
logger = logging.getLogger(__name__)
runner = CommandRunner(AppContext(verbose=True))

if "GNOME" not in os.environ.get("XDG_CURRENT_DESKTOP", "").upper():
	logger.critical("GNOME not detected in XDG_CURRENT_DESKTOP")
	exit(1)

if "gnome" not in os.environ.get("XDG_SESSION_DESKTOP", "").lower():
	logger.critical("GNOME session not detected")
	exit(1)

sleep(5)

for attempt in range(1, 4):
	if runner.run(["alt-panelmode", "--command=to-panel"]).returncode == 0:
		break
	sleep(3)
else:
	logger.critical("Error: Failed to switch panel mode after 3 attempts")
	exit(1)

autostart_name = os.path.basename(sys.argv[0]) + ".desktop"

system_autostart = Path(f"/etc/xdg/autostart/{autostart_name}")

home = Path.home()
destination_dir = home / ".config" / "autostart"
destination = destination_dir / autostart_name

if system_autostart.exists() and not destination.exists():
	try:
		destination_dir.mkdir(parents=True, exist_ok=True)
		shutil.copy2(system_autostart, destination)

		text = destination.read_text()
		new_text = text.replace("Hidden=false", "Hidden=true")

		if new_text != text:
			destination.write_text(new_text)

	except Exception as err:
		logger.warning(f"Warning: {err}")
