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

import platform

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() != 'bullseye':
    print("WARNING: The current long term supported platform is Debian 11 (bullseye)")
    print("WARNING: It is recommended to use only this platform to ensure stability and security")
    print("WARNING: To upgrade your system consult: https://docs.globaleaks.org/en/main/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.settings import Settings
from globaleaks.state import State, mail_exception_handler
from globaleaks.utils.process import drop_privileges, set_proc_title


set_proc_title("globaleaks")


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("-s", "--socks-host", type="string",
    help="set Socks host to use for Tor [default: %default]",
    dest="socks_host", default=Settings.socks_host)

parser.add_option("-r", "--socks-port", type="int",
    help="set Socks port to use for Tor [default: %default]",
    dest="socks_port", default=Settings.socks_port)

parser.add_option("-u", "--user", type="string",
    help="set the user to run as [default: current_user]",
    dest="user", default=None)

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

parser.add_option("-d", "--disable-csp", action='store_true',
    help="disable content security policy",
    dest="disable_csp", default=False)

parser.add_option("-z", "--devel-mode", action='store_true',
    help="set development mode [default: False]",
    dest="devel_mode", 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()


drop_privileges(Settings.user, Settings.uid, Settings.gid)


State.init_environment()


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

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:
    TwistedApplicationRunner(config).run()
except Exception as excep:
    print("Unable to start GlobaLeaks: %s" % excep)
    sys.exit(1)
