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