#! /usr/bin/python3
# -*- coding: utf-8 -*-
import os

import platform

import signal

import sys

# Avoid writing bytecode files at runtime
sys.dont_write_bytecode = True

this_directory = os.path.dirname(__file__)
root = os.path.abspath(os.path.join(this_directory, '..'))
sys.path.insert(0, root)

from globaleaks.utils.utility import get_distribution_codename

if get_distribution_codename() not in ['trixie', 'noble'] :
    print("WARNING: The recommended up-to-date platforms are Debian 13 (Trixie) and Ubuntu 24.04 (Noble)")
    print("WARNING: Use one of these platforms to ensure best stability and security")
    print("WARNING: To upgrade your system consult: https://docs.globaleaks.org/en/stable/user/admin/UpgradeGuide.html")


# this import seems unused but it is required in order to load the mocks
import globaleaks.mocks.twisted_mocks  # pylint: disable=W0611

# pylint: enable=no-name-in-module
from optparse import OptionParser

from twisted.python import usage

from twisted.scripts._twistd_unix import ServerOptions
from twisted.scripts._twistd_unix import UnixApplicationRunner as TwistedApplicationRunner

from globaleaks import __version__, DATABASE_VERSION
from globaleaks.rest.cache import Cache
from globaleaks.settings import Settings
from globaleaks.state import State, mail_exception_handler


def SIGUSR1_handler(*args):
    State.reset_cache = True


parser = OptionParser()

parser.add_option("-n", "--nodaemon", action='store_true',
    help="don't daemonize",
    dest="nodaemon", default=False)

parser.add_option("-i", "--ip", type="string",
    help="IP address used for listening [default: %default]",
    dest="ip", default=Settings.bind_address)

parser.add_option("-w", "--working-path", type="string",
    help="set the backend working directory",
    dest="working_path", default=None)

parser.add_option("-z", "--devel-mode", action='store_true',
    help="set development mode [default: False]",
    dest="devel_mode", default=False)

parser.add_option("-m", "--migrate-only", action='store_true',
    help="run only db and data migration scripts [default: False]",
    dest="migrate_only", default=False)

parser.add_option("-o", "--orm-debug", action='store_true',
    help="enable ORM debugging [default: False]",
    dest="orm_debug", default=False)

parser.add_option("-v", "--version", action='store_true',
    help="show the version of the software")

# here the options are parsed, because sys.argv array is whack below
(options, args) = parser.parse_args()

if options.version:
    print("GlobaLeaks version:", __version__)
    print("Database version:", DATABASE_VERSION)
    sys.exit(0)


Settings.load_cmdline_options(options)


State.bind_tcp_ports()


State.init_environment()


args = ['-y', Settings.backend_script]

if Settings.nodaemon:
    args += ['-n']
else:
    print("Going in background; log available at %s" % Settings.logfile)

args += ['--pidfile', Settings.pidfile_path]

sys.argv[1:] = args

sys.excepthook = mail_exception_handler

config = ServerOptions()

try:
    config.parseOptions()
except usage.error as ue:
    print("%s: %s" % (sys.argv[0], ue))
    sys.exit(1)

try:
    signal.signal(signal.SIGUSR1, SIGUSR1_handler)

    TwistedApplicationRunner(config).run()
except Exception as excep:
    print("Unable to start GlobaLeaks: %s" % excep)
    sys.exit(1)
