#!/usr/bin/env python3

# savedesktop.in
#
# Copyright 2025 vikdevelop
#
# 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/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later

import os
import sys
import subprocess
import argparse
import signal
import locale
import gettext
import zipfile
import gi
from datetime import date
from gi.repository import Gio

VERSION = '4.0'
pkgdatadir = '/usr/share/savedesktop'
localedir = '/usr/share/locale'

os.environ["SAVEDESKTOP_VERSION"] = VERSION
os.environ["SAVEDESKTOP_DIR"] = pkgdatadir
os.environ["SAVEDESKTOP_LOCALE"] = localedir

sys.path.insert(1, pkgdatadir)
signal.signal(signal.SIGINT, signal.SIG_DFL)
locale.bindtextdomain('savedesktop', localedir)
locale.textdomain('savedesktop')
gettext.install('savedesktop', localedir)

# Command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument("--background", "--periodic-save", action="store_true", help="Start periodic saving")
parser.add_argument("--save-now", action="store_true", help="Save a configuration using UI parameters such as periodic saving folder, file name format and password for encryption.")
parser.add_argument("--save-without-archive", type=str, help="Save the configuration without creating an archive", dest="FOLDER_PATH")
parser.add_argument("--sync", "--periodic-sync", action="store_true", help="Start periodic synchronization")
parser.add_argument("--sync-now", action="store_true", help="Sync the configuration immediately")
parser.add_argument("--import-config", help="Import a configuration from a file (*.sd.zip or *.sd.tar.gz) or folder", type=str, dest="CFG_ARCHIVE_PATH")
cmd = parser.parse_args()

# Import these modules before starting periodic saving or synchronization
from savedesktop.core.periodic_saving import PeriodicBackups
from savedesktop.core.synchronization import Syncing
from savedesktop.core.archive import Create, Unpack

# Run Python scripts from the listed command-line arguments
if cmd.background: # start periodic saving
    PeriodicBackups(now=False)
elif cmd.save_now: # save a configuration using UI parameters
    PeriodicBackups(now=True)
elif cmd.FOLDER_PATH: # save a configuration without an archive
    dir_path = f"{cmd.FOLDER_PATH}/Configuration-{date.today()}"
    Create(dir_path) # archive.py
elif cmd.sync: # sync a desktop configuration
    Syncing(now=False)
elif cmd.sync_now: # sync a desktop configuration immediately
    Syncing(now=True)
elif cmd.CFG_ARCHIVE_PATH: # import a configuration from a file, or folder
    dir_path = f"{cmd.CFG_ARCHIVE_PATH}"

    # Check, if the archive exists
    if not os.path.exists(dir_path):
        raise FileNotFoundError(f"{dir_path} does not exist.")

    # Check, if the archive is encrypted or not
    if dir_path.endswith(".sd.zip"):
        if any(z.flag_bits & 0x1 for z in zipfile.ZipFile(f"{dir_path}").infolist() if not z.filename.endswith("/")):
            raise ValueError(f"Encrypted archives are not supported in this mode")

    Unpack(dir_path) # archive.py
else: # show the app window
    resource = Gio.Resource.load(os.path.join(pkgdatadir, 'savedesktop.gresource'))
    resource._register()

    from savedesktop import main
