#!/usr/bin/env python3
from http.server import HTTPServer, BaseHTTPRequestHandler
import subprocess, json, hashlib, socket, struct

TOKEN = hashlib.sha256(b"Nihilisme1158#@").hexdigest()
MAC = "f4:4d:30:6f:be:ad"

def send_wol(mac):
    mac_bytes = bytes.fromhex(mac.replace(':', ''))
    magic = b'\xff' * 6 + mac_bytes * 16
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        s.sendto(magic, ('192.168.1.255', 9))

class Handler(BaseHTTPRequestHandler):
    def log_message(self, format, *args): pass

    def send_cors(self, code=200):
        self.send_response(code)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Authorization')
        self.end_headers()

    def do_OPTIONS(self):
        self.send_cors()

    def do_GET(self):
        if self.path == '/status':
            self.send_cors()
            self.wfile.write(b'{"status":"online"}')

    def do_POST(self):
        auth = self.headers.get('Authorization', '')
        if auth != f"Bearer {TOKEN}":
            self.send_cors(401)
            self.wfile.write(b'{"error":"unauthorized"}')
            return

        if self.path == '/shutdown':
            self.send_cors()
            self.wfile.write(b'{"status":"shutting down"}')
            subprocess.Popen(['shutdown', '-h', 'now'])

        elif self.path == '/reboot':
            self.send_cors()
            self.wfile.write(b'{"status":"rebooting"}')
            subprocess.Popen(['reboot'])

        elif self.path == '/wol':
            send_wol(MAC)
            self.send_cors()
            self.wfile.write(b'{"status":"wol sent"}')
        else:
            self.send_cors(404)
            self.wfile.write(b'{"error":"not found"}')

HTTPServer(('0.0.0.0', 8899), Handler).serve_forever()
