#!/usr/bin/python3

import argparse
import struct
import subprocess
import json
import sys

from os import environ,path
from impacket.krb5.ccache import CCache
from base64 import b64encode

home = ""
nethome = ""
vminfo = {}

def get_printers():
    printers = []
    try:
        result = subprocess.run(['lpstat', '-v'], capture_output=True, text=True, check=True)
        for line in result.stdout.splitlines():
            # Extrahiere den Druckernamen
            printer_name = line.split()[2].rstrip(':')
            ipp_url = f"ipp://192.168.122.1/printers/{printer_name}"
            printer = { 'Name': printer_name, 'IppURL': ipp_url }
            printers.append(printer)
        return printers
    except subprocess.CalledProcessError as e:
        sys.stderr.write(f"Fehler beim Abrufen der Drucker: {e}")
        return []

def get_groups(username):
    try:
        result = subprocess.run(['id', '-Gnz',  username], capture_output=True, text=True, check=True)
        groups = result.stdout.strip().split('\0')
        return groups
    except subprocess.CalledProcessError as e:
        sys.stderr.write(f"Fehler beim Abrufen der Gruppen: {e}")
        return []

def get_krb5 ():
    krb5 = {}
    ccachefilename = environ.get('KRB5CCNAME').replace('FILE:', '')
    if ccachefilename:
        try:
            ccache = CCache.loadFile(ccachefilename)
            cred = ccache.toKRBCRED()
            cred_enc = b64encode(cred)
            krb5['cred'] = cred_enc.decode('utf-8')
            krb5['starttime'] = ccache.credentials[0]['time']['starttime']
            krb5['endtime'] = ccache.credentials[0]['time']['endtime']
            krb5['renew_till'] = ccache.credentials[0]['time']['renew_till']
        except:
            sys.stderr.write("Fehler beim Ticket laden")
    return krb5

def get_mounts():
    mounts = []
    mounts.append({ 'Drive': 'H', 'RemotePath': '\\\\server.pn.steinbeis.schule' + nethome.replace('/srv/samba/schools','').replace('/','\\'), 'Name': 'Home_Server' })
    mounts.append({ 'Drive': 'T', 'RemotePath': '\\\\server.pn.steinbeis.schule\default-school\share', 'Name': 'Tausch' })
    return mounts

def get_user_folders():
    HOME="H:"
    if environ.get('HOME') != nethome:
        HOME="Y:"
    folders = []
    folders.append( {'Name': 'Personal', 'Path': f"{HOME}\Dokumente"} )
    folders.append( {'Name': 'My Pictures', 'Path': f"{HOME}\Bilder"} )
    folders.append( {'Name': 'My Music', 'Path': f"{HOME}\Musik"} )
    folders.append( {'Name': 'My Video', 'Path': f"{HOME}\Videos"} )
    return folders

def get_quickaccess():
    quickaccess = []
    quickaccess.append( 'H:\\transfer' )
    return quickaccess

def parse_args():
    parser = argparse.ArgumentParser()
    #parser.add_argument('input_file', help="File in kirbi (KRB-CRED) or ccache format")
    #parser.add_argument('output_file', help="Output file")
    return parser.parse_args()


def main():
    global home, nethome

    args = parse_args()

    home = environ.get('HOME')

    vminfo['User'] = environ.get('USER')
    vminfo['Groups'] = get_groups(environ.get('USER'))

    if 'teachers' in vminfo['Groups']:
        nethome = f"/srv/samba/schools/default-school/teachers/{vminfo['User']}"
    else:
        result = subprocess.run(['find', '/srv/samba/schools/default-school/students/', '-name', vminfo['User'], '-maxdepth', '2', '-type', 'd'], capture_output=True, text=True, check=False)
        nethome = result.stdout.splitlines()[0]

    vminfo['Printers'] = get_printers()
    vminfo['krb5'] = get_krb5()
    vminfo['Mounts'] = get_mounts()
    vminfo['UserShellFolders'] = get_user_folders()
    vminfo['QuickAccess'] = get_quickaccess()

    vminfo_json = json.dumps(vminfo, ensure_ascii=False, indent=4)
    print(vminfo_json)

if __name__ == '__main__':
    main()


