#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Main
#
# Copyright (C) 2014  Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): Vojtech Trefny <vtrefny@redhat.com>
#
# ---------------------------------------------------------------------------- #

import os
import sys
import atexit
import pid

import tempfile

import socketserver

from blivetgui.communication.server import BlivetUtilsServer

# ---------------------------------------------------------------------------- #


class BlivetGUIServer(socketserver.UnixStreamServer):
    """ Custom UnixStreamServer instance
    """

    quit = False
    other_running = False

    def serve_forever(self):  # pylint: disable=arguments-differ
        """ Serve until interrupted
        """
        while not self.quit:
            self.handle_request()  # pylint: disable=no-member

# ---------------------------------------------------------------------------- #


def remove_temp_files(files, folders=None):
    """ Remove temporary files and folders
    """

    try:
        for file_name in files:
            os.unlink(file_name)

        if folders:
            for folder_name in folders:
                os.rmdir(folder_name)

    except OSError:
        pass


def create_sock_file():
    """ Create a sock file
    """

    tempdir = tempfile.mkdtemp()
    socket = tempdir + "/blivet-gui.sock"
    atexit.register(remove_temp_files, (socket,), (tempdir,))

    os.chmod(tempdir, 0o705)

    return socket


def main(argv):
    """ Main for blivet-gui-daemon
    """

    if len(argv) != 1:
        print("Expected exactly one positional argument %d given" % len(argv))
        sys.exit(1)

    if os.geteuid() != 0:
        print("Root privileges required to run blivet-gui-daemon")
        sys.exit(1)

    sock_file = create_sock_file()

    server = BlivetGUIServer(sock_file, BlivetUtilsServer)

    user_id = int(argv[0])
    os.chown(sock_file, user_id, user_id)
    os.chmod(sock_file, 0o600)

    pidfile = pid.PidFile(pidname="blivet-gui-daemon", register_term_signal_handler=False)
    try:
        pidfile.create()
    except pid.PidFileError:
        server.other_running = True
    else:
        atexit.register(remove_temp_files, (pidfile.filename,))

    print(sock_file)
    sys.stdout.flush()

    sys.stdout = sys.stderr

    server.serve_forever()


if __name__ == "__main__":
    main(sys.argv[1:])
