#!/usr/bin/python3
import gi, os, sys, jwmkit_utils
from subprocess import run, PIPE
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GdkPixbuf

# JWM Kit - A set of Graphical Apps to simplify use of JWM (Joe's Window Manager) <https://codeberg.org/JWMKit/JWM_Kit>
# Copyright © 2020-2022 Calvin Kent McNabb <apps.jwmkit@gmail.com>
#
# This file is part of JWM Kit.
#
# JWM Kit is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2,
# as published by the Free Software Foundation.
#
# JWM Kit 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 JWM Kit.  If not, see <https://www.gnu.org/licenses/>.


def prompt(command):
    pw_data = jwmkit_utils.private_entry(win)
    if sys.argv[1] == 'sudop':
        su = 'sudo -S'
    if not pw_data[0]:
        return
    else:
        if command.startswith(su):
            cmd = command
        else:
            cmd = 'echo "{}" | {} {}  && echo success'.format(pw_data[1], su, command)
        auth_check(cmd)
        return cmd


def auth_check(cmd):
    check = run(cmd, shell=True, stdout=PIPE)
    check = check.stdout.decode()
    if "success" in check:
        print("OK")
    else:
        print("Fail")
        prompt(cmd)
        return


def reboot_command(widget):
    if len(sys.argv) < 2:
        cmd = 'dbus-send --system --print-reply --dest="org.freedesktop.ConsoleKit"' \
              ' /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.Restart'
    elif sys.argv[1] == 'x':
        cmd = 'su-to-root -X -c /sbin/reboot'
    elif sys.argv[1].startswith('nox'):
        cmd = sys.argv[1][4:]
        cmd = '{} -e "su-to-root -c /sbin/reboot"'.format(cmd)
    elif sys.argv[1].startswith('su:'):
        cmd = sys.argv[1][3:]
        cmd = '{} -e "su -c /sbin/reboot"'.format(cmd)
    elif sys.argv[1].startswith('custom:'):
        cmd = sys.argv[1].split(':')[1]
    elif sys.argv[1] in ('sudoa', 'askpass'):
        cmd = 'sudo -A /sbin/reboot'
    elif sys.argv[1].startswith("term"):
        cmd = sys.argv[1].split(":")
        cmd = '{} -e "{} /sbin/reboot"'.format(cmd[1], cmd[2])
    elif sys.argv[1] in ('sysd', 'systemd', 'systemctl'):
        cmd = 'systemctl reboot'
    elif sys.argv[1] in ('loginctl', 'elogind'):
        cmd = 'loginctl reboot'
    elif sys.argv[1] == 'sudop':
        prompt("/sbin/reboot")
        return
    elif sys.argv[1] in ('sudo', 'su-to-root -X -c', 'gksu', 'gksudo', 'doas'):
        cmd = sys.argv[1] + " /sbin/reboot"
    elif sys.argv[1] == 'puppy':
        cmd = '/usr/bin/wmreboot'
    elif sys.argv[1] == 'pkexec':
        cmd = 'pkexec reboot'
    else:
        cmd = "/sbin/reboot"
    if cmd:
        os.system(cmd)


def shutdown_command(widget):
    if len(sys.argv) < 2:
        cmd = 'dbus-send --system --print-reply --dest="org.freedesktop.ConsoleKit"' \
              ' /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.Stop'
    elif sys.argv[1] in ('dbus', 'consolekit'):
        cmd = 'dbus-send --system --print-reply --dest="org.freedesktop.ConsoleKit"' \
              ' /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.Stop'
    elif sys.argv[1] == 'x':
        cmd = 'su-to-root -X -c /sbin/poweroff'
    elif sys.argv[1].startswith('nox'):
        cmd = sys.argv[1][4:]
        cmd = '{} -e "su-to-root -c /sbin/poweroff"'.format(cmd)
    elif sys.argv[1].startswith('su:'):
        cmd = sys.argv[1][3:]
        cmd = '{} -e "su -c /sbin/poweroff"'.format(cmd)
    elif sys.argv[1].startswith('custom:'):
        cmd = sys.argv[1].split(':')[2]
    elif sys.argv[1] in ('sudoa', 'askpass'):
        cmd = 'sudo -A /sbin/poweroff'
    elif sys.argv[1].startswith("term"):
        cmd = sys.argv[1].split(":")
        cmd = '{} -e "{} /sbin/poweroff"'.format(cmd[1], cmd[2])
    elif sys.argv[1] in ('sysd', 'systemd', 'systemctl'):
        cmd = 'systemctl poweroff'
    elif sys.argv[1] in ('loginctl', 'elogind'):
        cmd = 'loginctl poweroff'
    elif sys.argv[1] == 'sudop':
        prompt("/sbin/poweroff")
        return
    elif sys.argv[1] in ('sudo', 'su-to-root -X -c', 'gksu', 'gksudo', 'doas'):
        cmd = sys.argv[1] + " /sbin/poweroff"
    elif sys.argv[1] in ('puppy', 'wm'):
        cmd = '/usr/bin/wmpoweroff'
    elif sys.argv[1] == 'pkexec':
        cmd = 'pkexec poweroff'
    else:
        cmd = "/sbin/poweroff"
    if cmd:
        os.system(cmd)


class GridWindow(Gtk.Window):

    def __init__(self):

        Gtk.Window.__init__(self, title="Logout  " + os.environ["USER"])
        try:
            self.set_icon_from_file('/usr/share/pixmaps/jwmkit/exitgray.svg')
        except gi.repository.GLib.Error:
            self.set_icon_name("application-exit")
        self.set_border_width(6)
        self.set_hexpand(False)
        grid = Gtk.Grid(column_homogeneous=True, column_spacing=10, row_spacing=10)
        self.add(grid)

        button_image = Gtk.Image()
        pb = GdkPixbuf.Pixbuf.new_from_file_at_scale('/usr/share/pixmaps/jwmkit/cancelgray.svg', 50, 50, preserve_aspect_ratio=True)
        button_image.set_from_pixbuf(pb)
        self.cancel_button = Gtk.Button(image=button_image, label="Cancel")

        button_image = Gtk.Image()
        pb = GdkPixbuf.Pixbuf.new_from_file_at_scale('/usr/share/pixmaps/jwmkit/exitgray.svg', 50, 50, preserve_aspect_ratio=True)
        button_image.set_from_pixbuf(pb)
        self.logout_button = Gtk.Button(image=button_image, label="Logout")

        button_image = Gtk.Image()
        pb = GdkPixbuf.Pixbuf.new_from_file_at_scale('/usr/share/pixmaps/jwmkit/restartgray.svg', 50, 50, preserve_aspect_ratio=True)
        button_image.set_from_pixbuf(pb)
        self.reboot_button = Gtk.Button(image=button_image, label="Reboot")

        button_image = Gtk.Image()
        pb = GdkPixbuf.Pixbuf.new_from_file_at_scale('/usr/share/pixmaps/jwmkit/shutdowngray.svg', 50, 50, preserve_aspect_ratio=True)
        button_image.set_from_pixbuf(pb)
        self.shutdown_button = Gtk.Button(image=button_image, label="Shutdown")

        self.cancel_button.set_image_position(Gtk.PositionType.TOP)
        self.logout_button.set_image_position(Gtk.PositionType.TOP)
        self.reboot_button.set_image_position(Gtk.PositionType.TOP)
        self.shutdown_button.set_image_position(Gtk.PositionType.TOP)

        self.cancel_button.set_always_show_image(True)
        self.logout_button.set_always_show_image(True)
        self.reboot_button.set_always_show_image(True)
        self.shutdown_button.set_always_show_image(True)

        self.cancel_button.set_property("width-request", 120)
        self.logout_button.set_property("width-request", 120)
        self.reboot_button.set_property("width-request", 120)
        self.shutdown_button.set_property("width-request", 120)

        # place buttons on grid
        grid.attach(self.cancel_button, 0, 0, 6, 11)
        grid.attach(self.logout_button, 11, 0, 6, 11)
        grid.attach(self.reboot_button, 0, 11, 6, 11)
        grid.attach(self.shutdown_button, 11, 11, 6, 11)

        # link buttons to actions
        self.cancel_button.connect("clicked", Gtk.main_quit)
        self.logout_button.connect("clicked", self.logout_command)
        self.reboot_button.connect("clicked", reboot_command)
        self.shutdown_button.connect("clicked", shutdown_command)

    def disable_buttons(self):
        self.cancel_button.set_sensitive(False)
        self.logout_button.set_sensitive(False)
        self.reboot_button.set_sensitive(False)
        self.shutdown_button.set_sensitive(False)

    # button actions
    def logout_command(self, widget):
        self.disable_buttons()
        if len(sys.argv) < 2:
            os.system("jwm -exit")
        elif sys.argv[1] in ['puppy', '-puppy']:
            os.system("/usr/bin/wmexit")
        else:
            os.system("jwm -exit")


pid = str(os.getpid())
pids = os.popen('pgrep -x "jwmkit_logout"').read()
pids = str(pids).split('\n')
if pid in pids:
    pids.remove(pid)
pids = [id for id in pids if id]
if pids:
    os.system("kill -s TERM " + pids[0])
    os.sys.exit()

# Remove leading dashes ( - ) from input parameters
if len(sys.argv) >= 2:
    while sys.argv[1][0] == "-": sys.argv[1] = sys.argv[1][1:]
    sys.argv[1] = sys.argv[1].lower().replace('root -x -c', 'root -X -c')
else:
    # check parameters are defined in configuration file
    su = jwmkit_utils.get_su('logout')
    if su:
        if su.endswith('_r'):
            su = su[:-2]
        sys.argv.append(su)

win = GridWindow()
win.connect("delete-event", Gtk.main_quit)
win.set_resizable(False)
win.set_position(Gtk.WindowPosition.CENTER)
win.show_all()
Gtk.main()

#  Detect systemd command (returns systemd or init, etc)
#   ps --no-headers -o comm 1

