named tuples in tyshell for better readability
[saartuer.git] / tyshell
1 #!/usr/bin/python3
2 import os
3 import readline
4 import shlex
5 import sys
6 import subprocess
7 import socket
8 import pwd
9 import grp
10 from collections import namedtuple
11
12 tuerSock = "/run/tuer.sock"
13
14 # use a histfile
15 histfile = os.path.join(os.path.expanduser("~"), ".tyshellhist")
16 try:
17     readline.read_history_file(histfile)
18 except IOError:
19     pass
20 import atexit
21 atexit.register(readline.write_history_file, histfile)
22
23 # available commands
24 def helpcmd(c):
25         if (len(c) > 1):
26                 print(commands.get(c[1],(None,'Can\'t find help for command %s'%(c[1]))).helpstring)
27         else:
28                 print("Available commands: %s" % ", ".join(sorted(commands.keys())))
29                 print("Use 'help command' to get more information on the command 'command'")
30
31 def extcmd(cmd):
32         def run(c):
33                 ret = subprocess.call(cmd)
34                 if ret != 0:
35                         print("Command returned non-zero exit statis %d" % ret)
36         return run
37
38 def sendcmd(addr, cmd):
39         def run(c):
40                 print("206 Sending command %s..." % (cmd))
41                 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
42                 s.connect(addr)
43                 s.settimeout(60.0)
44                 s.send(cmd.encode())
45                 data = s.recv(256)
46                 s.close()
47                 print(data.decode('utf-8'))
48         return run
49
50 def exitcmd(c):
51         print("Bye")
52         return True
53
54 def whocmd(c):
55         for n in grp.getgrnam("tuer").gr_mem:
56                 p = pwd.getpwnam(n)
57                 print (p.pw_name, " - ", p.pw_gecos)
58
59 def alias (cmds, aliases):
60         for newname, oldname in aliases.items():
61                 cmds[newname] = cmds[oldname]
62         return cmds
63
64 CmdEntry = namedtuple('CmdEntry','function helpstring')
65
66 commands = alias({
67         'exit': CmdEntry(exitcmd, 'Quits this shell'),
68         'help': CmdEntry(helpcmd, 'Helps you getting to know the available commands'),
69         'open': CmdEntry(sendcmd(tuerSock, 'unlock'), 'Will try to unlock the apartment door'),
70         'buzz': CmdEntry(sendcmd(tuerSock, 'buzz'), 'Will buzz the buzzer for the street door'),
71         'who': CmdEntry(whocmd, 'Shows the list of people, who are allowed to control this system'),
72 },{
73         # aliases
74         'unlock': 'open',
75 })
76
77 def complete_command(cmd):
78         '''returns a list of commands (as strings) starting with cmd'''
79         return list(filter(lambda x: x.startswith(cmd), commands.keys()))
80 readline.set_completer(lambda cmd, num: (complete_command(cmd)+[None])[num]) # wrap complete_command for readline's weird completer API
81 readline.parse_and_bind("tab: complete") # run completion on tab
82
83 # input loop
84 print("Welcome to tyshell. Use help to see what you can do.")
85 while True:
86         try:
87                 command = input("$ ")
88         except EOFError:
89                 print()
90                 break
91         command = shlex.split(command)
92         if not len(command): continue
93         # find suiting commands
94         if command[0] in commands: # needed in case a complete command is a prefix of another one
95                 cmdoptions = [command[0]]
96         else:
97                 cmdoptions = complete_command(command[0])
98         # check how many we found
99         if len(cmdoptions) == 0: # no commands fit prefix
100                 print("Command %s not found. Use help." % command[0])
101         elif len(cmdoptions) == 1: # exactly one command fits (prefix)
102                 try:
103                         res = commands[cmdoptions[0]].function(command)
104                         if res: break
105                 except Exception as e:
106                         print("Error while executing %s: %s" % (command[0], str(e)))
107         else: # multiple commands fit the prefix
108                 print("Ambiguous command prefix, please choose one of the following:")
109                 print("\t", " ".join(cmdoptions))
110                 # TODO: put current "command[0]" into the shell for the next command, but such that it is deletable with backspace
111