#!/usr/bin/python3

"""
    N4D Client

    N4D client cli

    Copyright (C) 2024  Enrique Medina Gremaldos <quique@necos.es>

    This program is free software: you can redistribute it and/or modify it under
    the terms of the GNU General Public License as published by the Free Software
    Foundation, either version 3 of the License, or (at your option) any later
    version.

    This program 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
    this program. If not, see <http://www.gnu.org/licenses/>.
"""

import n4d.client

import os
import sys
import getpass
import time
import argparse
import json

def main():
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--address", help="server address",default="https://127.0.0.1:9779")
    parser.add_argument("-u", "--user", help="user name")
    parser.add_argument("-p", "--password", help="user password")
    parser.add_argument("-k", "--key", help="Use given key instead of password. If no user is specified, master key is assumed")
    parser.add_argument("-i", "--interactive", help="interactive login",action="store_true")
    parser.add_argument("-r", "--root", help="Use local master ticket to run client, no address or login arguments are required",action="store_true")

    parser.add_argument("-j", "--json-output", help="prints call result in json format", action="store_true")
    parser.add_argument("-J", "--json-input", help="reads json call arguments structure from stdin", action="store_true")

    parser.add_argument("-t", "--ticket", help="Use local ticket to run client, no address or login arguments are required",action="store_true")
    parser.add_argument("action",type=str, help="call, get-methods, validate-user, create-ticket")
    parser.add_argument("call",nargs='*',default="[]")
    args = parser.parse_args()
    
    cuser= args.user
    cpassword=args.password
    caddress=args.address
    ccredential=None
    
    if (args.root and args.ticket):
        print("root and ticket options are incompatible between them",file=sys.stderr)
        sys.exit(1)
    
    if (args.ticket):
        if (not cuser):
            cuser=getpass.getuser()
        
        ckey = n4d.client.Key.user_key(cuser)
        
        if (not ckey.valid()):
            print("Failed to load user key",file=sys.stderr)
            sys.exit(1)
        
        ccredential = n4d.client.Credential(user=cuser,key=ckey)
        caddress="https://localhost:9779"
    
    if (args.key):
        
        ckey = n4d.client.Key(args.key)
        
        if (cuser):
            ccredential = n4d.client.Credential(user=cuser,key=ckey)
        else:
            ccredential = n4d.client.Credential(key=ckey)
        
        if (not ccredential.key.valid()):
            print("Warning, provided key seems invalid",file=sys.stderr)
            
    
    if (args.root):
        
        ckey = n4d.client.Key.master_key()

        if (not ckey.valid()):
            print("Failed to read master key",file=sys.stderr)
            sys.exit(1)
        
        ccredential = n4d.client.Credential(key=ckey)
        caddress="https://localhost:9779"
        
    if (not ccredential):
        if (not cuser):
            cuser=getpass.getuser()
        
        if (args.interactive):
            print("user: %s"%(cuser),file=sys.stderr)
            cpassword=getpass.getpass("password: ")
        
        ccredential = n4d.client.Credential(user=cuser,password=cpassword)
        
    if (args.action=="call"):
        
        if (len(args.call)==0):
            sys.exit(1)
    
        tmp=args.call[0].split('.')
        #print(tmp)
        plugin = None
        method = None
    
        if (len(tmp)==1):
            method=tmp[0]
        elif (len(tmp)==2):
            plugin=tmp[0]
            method=tmp[1]
        else:
            sys.exit(1)

        arguments=None

        if (args.json_input):
            raw = sys.stdin.read()
            arguments = json.loads(raw)
        else:
            if (len(args.call)>1):
                arguments=args.call[1]

            if (arguments):
                tmp = arguments.replace('\'','\"')
                data=json.loads(tmp)
                arguments=data
                #print(data)
            else:
                arguments=[]
            
        client = n4d.client.Client(caddress,credential=ccredential)
        proxy = n4d.client.Proxy(client,plugin,method)
        result = proxy.call(*arguments)

        if (args.json_output):
            print(json.dumps(result))
        else:
            print(result)
    
    if (args.action=="get-methods"):
        client = n4d.client.Client(caddress,credential=ccredential)
        data=client.get_methods()
        
        rows=[]
        max_columns=0
        for p in data:
            
            for m in data[p]:
                columns=[]
                columns.append(p)
                columns.append(m)
                
                for pr in data[p][m]:
                    columns.append(pr)
                    columns.append(str(data[p][m][pr]))
                
                rows.append(columns)
                if (len(columns)>max_columns):
                    max_columns=len(columns)
        
        csizes=[0]*max_columns
        
        for r in rows:
            for n in range(len(r)):
                x=len(r[n])
                if (x>csizes[n]):
                    csizes[n]=x
                
        for row in rows:
            line=""
            for n in range(len(row)):
                col=row[n]
                line+=col
                spaces = csizes[n]-len(col)
                for s in range(spaces):
                    line+=" "
                line+="    "
                
            print(line)
        
    if (args.action=="validate-user"):
        client = n4d.client.Client(caddress,credential=ccredential)
        try:
            data=client.validate_user()
            groups=""
            for g in data[1]:
                groups+=g+" "
            print(groups)
            
        except n4d.client.AuthenticationError as e:
            print("Failed")
            sys.exit(1)
            
        except Exception as e:
            sys.exit(1)
    
    if (args.action=="create-ticket"):
        if (not cuser):
            cuser=getpass.getuser()
            
        client = n4d.client.Client(caddress,user=cuser,password="")

        try:
            client.create_ticket()
        except Exception as e:
            print(str(e),file=sys.stderr)
            sys.exit(1)
        
    sys.exit(0)

if __name__=="__main__":
    main()


