# This file is Copyright 2010 by the GPSD project
# SPDX-License-Identifier: BSD-2-clause
"""
gpsdfake - a fake gpsd server that spews specified data at gpsd clients.
"""
from __future__ import print_function
import socket
try:
    import socketserver
except:
    import SocketServer as socketserver  # until the true death of Python 2
import sys
import time

class FakeHandler(socketserver.BaseRequestHandler):
    "Instantiated once per connection to the server."
    def handle(self):
        try:
            global lines
            # self.request is the TCP socket connected to the client
            # Read the client's ?WATCH request.
            self.data = self.request.recv(1024).strip()
            # We'd like to send a fake banner to the client on startup,
            # but there's no (documented) method for that.  We settle
            # for shipping on first request.
            self.request.send(b'{"class":"VERSION",'
                              b'"version":"gpsdfake-3","rev":"3",'
                              b'"proto_major":3,"proto_minor":1}\r\n')
            # Perpetually resend the data we have specified
            while True:
                for line in lines:
                    self.request.send(line)
                    time.sleep(0.5)
        except Exception:
            pass

if __name__ == "__main__":
    (HOST, PORT) = "localhost", 2947

    try:
        if len(sys.argv) <= 1:
            sys.stderr.write("gpsdfake: requires a file argument.\n")
            sys.exit(1)

        lines = open(sys.argv[1], 'rb').readlines()

        # Create the server, binding to localhost on port 2947
        server = socketserver.TCPServer((HOST, PORT), FakeHandler)

        # Activate the server; this will keep running until you
        # interrupt the program with Ctrl-C
        server.serve_forever()
    except KeyboardInterrupt:
        print()
    except socket.error as e:
        print(e.args[1])
    sys.exit(0)

# The following sets edit modes for GNU EMACS
# Local Variables:
# mode:python
# End:
# vim: set expandtab shiftwidth=4
