#!/usr/bin/python3

import gi
gi.require_version("CinnamonDesktop", "3.0")
from gi.repository import CinnamonDesktop, GLib

import sys
import os
import pwd
import subprocess

class Main:
    def __init__(self, user):
        self.user = user
        CinnamonDesktop.installer_install_packages (["samba"], self.on_install_finished)

    def on_install_finished(self, success, data=None):
        ret = 0

        if not success:
            ret = -1
        else:
            # Add the user to the sambashare group
            try:
                cp = subprocess.run(["usermod", "-a", "-G", "sambashare", self.user], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
                ret = cp.returncode
            except subprocess.CalledProcessError as e:
                print(str(e))
                ret = e.returncode

        # Set firewall rules to allow Samba through UFW
        if os.path.exists("/usr/sbin/ufw"):
            subprocess.run(["/usr/sbin/ufw", "allow", "out", "proto", "tcp", "from", "any", "to", "any", "port", "139,445"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            subprocess.run(["/usr/sbin/ufw", "allow", "out", "proto", "udp", "from", "any", "to", "any", "port", "137,138"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            subprocess.run(["/usr/sbin/ufw", "allow", "in", "proto", "tcp", "from", "any", "to", "any", "port", "139,445"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            subprocess.run(["/usr/sbin/ufw", "allow", "in", "proto", "udp", "from", "any", "to", "any", "port", "137,138"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        ml.quit()
        exit(ret)

if __name__ == "__main__":
    ml = GLib.MainLoop.new(None, True)

    # prefer using the uid provided by pkexec to the command line argument. if
    # a user authenticated via pkexec then he should only be able to add
    # himself to the group.
    uid = os.getenv("PKEXEC_UID", None)

    if uid != None:
        uid = int(uid)
        passwd = pwd.getpwuid(uid)
        user = passwd[0]
    elif len(sys.argv) == 2:
        user = sys.argv[1]
    else:
        print("No target uid in environment or on command line found.")
        exit(-1)

    main = Main(user)
    ml.run()
