#!/usr/bin/python

import glob, sys, subprocess, os, re, socket

def setup_samba():
    mythhome = subprocess.check_output("lh_home_check.sh").decode('utf-8').strip()
    excludes = ['mysql','srv']
    print("    Activating samba file sharing")
    usersamba=mythhome+"/templates/smb.conf"
    subprocess.call(["pacman", "-S", "--noconfirm", "samba", "avahi"])
    if not os.path.exists("/etc/samba"):
        print("    Creating directory /etc/samba")
        try:
            os.makedirs("/etc/samba")
        except:
            pass

    if os.path.exists(usersamba):
        print("    Using user provided config file " + usersamba)
        subprocess.call(["install", "-Dm755",  usersamba, "/etc/samba/smb.conf"])
    else:
        #Samba_media = systemconfig.get("Samba_media")
        #Samba_home = systemconfig.get("Samba_home")
        smreadonly = "yes"
        shreadonly = "yes"
        domain = "WORKGROUP"
        servername = socket.gethostname()

        try:
            f = open("/usr/share/linhes/templates/smb.conf.template",'r')
            t_smbconf = f.readlines()
            f.close()
        except:
            print("   Couldn't open samba template file")
            return

        try:
            f = open("/etc/samba/smb.conf",'w')
        except:
            print("   Couldn't open samba file")
            return

        for line in t_smbconf:
            outline = line
            if re.match("^.*workgroup", line):
                print("    Setting workgroup to " + domain)
                outline="   workgroup = %s\n" %domain
                print("     " + outline)
            if re.match("^.* server string",line):
                print("    Setting server name to " + servername)
                outline="   server string = %s\n" %servername
                print("     " + outline)
            f.write(outline)

        outline="include =  %s/templates/user.shares \n" %mythhome
        f.write(outline)
        outline="include =  /etc/samba/smb.conf.media\n"
        f.write(outline)
        outline="include =  /etc/samba/smb.conf.home\n"
        f.write(outline)
        f.close()

        print("    Writing smb.conf.media")
        try:
            f = open("/etc/samba/smb.conf.media","w")
        except:
            print("*   Couldn't open smb.conf.media")
            return

        shares = scan_for_shares()
        medialines='''
[%s]
path = %s
public = yes
only guest = yes
writeable  = %s
printable = no
force user = mythtv
force group = mythtv
create mask = 0755\n'''
        new_share=[]
        excludes
        for share in shares:
            share_name = share.split("/")[-1]
            share_path = share
            f.write(medialines %(share_name,share_path,smreadonly) )
            print(medialines %(share_name,share_path,smreadonly) )
            excludeline = 'veto files = '
            for exclude in excludes:
                excludeline+= ''' /%s/ ''' %exclude

            if excludes != []:
                f.write( excludeline)
                f.write("\n")

        f.close()
        print("    Writing smb.conf.home")
        try:
                f = open("/etc/samba/smb.conf.home","w")
        except:
            print("    Couldn't open smb.conf.home")
            return
        homelines='''
[home]
path = %s
public = yes
only guest = yes
writeable  = %s
printable = no
force user = mythtv
force group = mythtv
create mask = 0755 ''' %(mythhome,shreadonly)
        f.write(homelines)
        f.close()
        print("     " + homelines)

    print("\n    Creating samba user mythtv")
    os.system("(echo mythtv; echo mythtv) | smbpasswd -sa mythtv")
    print("\n    Starting SMB, NMB and avahi services")
    subprocess.call(["systemctl", "enable", "--now", "smb.service"])
    subprocess.call(["systemctl", "enable", "--now", "nmb.service"])
    subprocess.call(["systemctl", "enable", "--now", "avahi-daemon.service"])
    print("\n    Finished setting up samba file sharing")


def scan_for_shares():
    import configparser
    config = configparser.RawConfigParser()
    file_list=glob.glob("/etc/storage.d/*.conf")
    share_list = ['/data/storage/disk0']
    for conf_file in file_list:
        try:
            print("    reading in %s" %conf_file)
            config.read(conf_file)
            shareable = config.get('storage','shareable')
            if shareable == "True" :
                mp = config.get('storage','mountpoint')
                share_list.append(mp)
#                if config.get('storage','mmount') == "True" :
#                    share_list.append("/myth")
        except:
            print("    Couldn't open %s for reading" %conf_file)
    return share_list


def setup_fileshare():
    setup_samba()

if __name__ == "__main__":
    setup_fileshare()
