#! /usr/bin/python

import os
import SocketServer

class FwTCPHandler(SocketServer.BaseRequestHandler):
    """
    The request handler class for our server.
    (see https://docs.python.org/2/library/socketserver.html)

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    commands = {"poweroff", "reboot"}

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()

        if self.data in FwTCPHandler.commands:
            os.system("systemctl " + self.data)
        else:
            print("Unknown command: " + self.data)

if __name__ == "__main__":
    HOST, PORT = "0.0.0.0", 2017

    # Create the server, binding to all my IP addresses on port 2017
    server = SocketServer.TCPServer((HOST, PORT), FwTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()
