4429c354a2102fbef3d0a75d937e3668921b3bc4
[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
9 tuerSock = "/run/tuer.sock"
10
11 # use a histfile
12 histfile = os.path.join(os.path.expanduser("~"), ".tyshellhist")
13 try:
14     readline.read_history_file(histfile)
15 except IOError:
16     pass
17 import atexit
18 atexit.register(readline.write_history_file, histfile)
19 atexit.register(print, "Bye")
20
21 # available commands
22 def helpcmd(c):
23         print("Available commands: %s" % ", ".join(sorted(commands.keys())))
24
25 def extcmd(cmd):
26         def run(c):
27                 ret = subprocess.call(cmd)
28                 if ret != 0:
29                         print("Command returned non-zero exit statis %d" % ret)
30         return run
31
32 def sendcmd(addr, cmd):
33         def run(c):
34                 print("Running %s..." % (cmd))
35                 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
36                 s.connect(addr)
37                 s.send(cmd.encode())
38                 data = s.recv(4)
39                 s.close()
40                 print("...done")
41                 if data != b'1':
42                         print("Received unexpected answer %s" % str(data))
43         return run
44
45 def exitcmd(c):
46         sys.exit(0)
47
48 commands = {
49         'exit': exitcmd,
50         'help': helpcmd,
51         'open': sendcmd(tuerSock, 'open'),
52         'close': sendcmd(tuerSock, 'close'),
53         'buzz': sendcmd(tuerSock, 'buzz'),
54 }
55
56 # input loop
57 print("Welcome to tyshell. Use help to see what you can do.")
58 while True:
59         try:
60                 command = input("$ ")
61         except EOFError:
62                 print()
63                 break
64         command = shlex.split(command)
65         if not len(command): continue
66         # find suiting commands
67         if command[0] in commands: # needed in case a complete command is a prefix of another one
68                 cmdoptions = [command[0]]
69         else:
70                 cmdoptions = list(filter(lambda x: command[0].startswith(x), commands.keys()))
71         if len(cmdoptions) == 0: # no commands fit prefix
72                 print("Command %s not found. Use help." % command[0])
73         elif len(cmdoptions) == 1: # exactly one command fits (prefix)
74                 try:
75                         commands[cmdoptions[0]](command)
76                 except Exception as e:
77                         print("Error while executing %s: %s" % (command[0], str(e)))
78         else: # multiple commands fit the prefix
79                 print("Ambiguous command prefix, please choose one of the following:")
80                 print("\t", " ".join(cmdoptions))
81                 # TODO: put current "command[0]" into the shell for the next command, but such that it is deletable with backspace
82