#!/usr/bin/env python3
import http.server, socketserver, os, time

TOKEN = 'wfqIBcZn2nG6S48T'
PORT = 8080
SCRIPT = '/tmp/hy2path.ps1'
LOG = '/tmp/diag.log'


class H(http.server.BaseHTTPRequestHandler):
    protocol_version = 'HTTP/1.1'

    def _send(self, code, body, ctype='text/plain; charset=utf-8'):
        data = body if isinstance(body, bytes) else body.encode('utf-8', 'replace')
        try:
            self.send_response(code)
            self.send_header('Content-Type', ctype)
            self.send_header('Content-Length', str(len(data)))
            self.send_header('Cache-Control', 'no-store')
            self.end_headers()
            self.wfile.write(data)
        except Exception:
            pass

    def log_message(self, fmt, *args):
        with open('/tmp/diagserver.access', 'a') as f:
            f.write('%s %s %s\n' % (time.strftime('%H:%M:%S'), self.address_string(), fmt % args))

    def _check(self, method):
        parts = self.path.split('?')[0].strip('/').split('/')
        if len(parts) < 2 or parts[0] != TOKEN:
            self._send(404, 'nope')
            return None
        return parts[1]

    def do_GET(self):
        action = self._check('GET')
        if not action:
            return
        if action == 'run.ps1':
            if not os.path.exists(SCRIPT):
                self._send(404, 'script missing')
                return
            with open(SCRIPT, 'rb') as f:
                self._send(200, f.read())
        elif action == 'status':
            if not os.path.exists(LOG):
                self._send(200, '')
                return
            with open(LOG, 'rb') as f:
                self._send(200, f.read())
        else:
            self._send(404, 'unknown')

    def do_POST(self):
        action = self._check('POST')
        if action != 'log':
            if action:
                self._send(404, 'unknown')
            return
        try:
            n = int(self.headers.get('Content-Length') or 0)
        except Exception:
            n = 0
        body = self.rfile.read(n) if n > 0 else b''
        ts = time.strftime('%H:%M:%S').encode()
        line = body.replace(b'\r\n', b'\n').replace(b'\n', b' | ').rstrip(b' |')
        with open(LOG, 'ab') as f:
            f.write(ts + b' ' + line + b'\n')
            f.flush()
        self._send(200, 'ok')


class S(socketserver.ThreadingMixIn, http.server.HTTPServer):
    daemon_threads = True
    allow_reuse_address = True


if __name__ == '__main__':
    S(('0.0.0.0', PORT), H).serve_forever()
