#!/usr/bin/python3
# coding: utf-8
# Copyright (c) 2024 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
import os
import sys
import cgi
import logging
from hashlib import sha256
from http.server import BaseHTTPRequestHandler, HTTPServer
import ecdsa
import ecdsa.util

private_key = None


class SignatureHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={
                'REQUEST_METHOD': 'POST',
                'CONTENT_TYPE': self.headers['Content-Type'],
            }
        )
        item = form['file']
        input_data = item.file.read()
        sig = private_key.sign(input_data, sigencode=ecdsa.util.sigencode_der)
        self.send_response(200)
        self.send_header('Content-type', 'application/octet-stream')
        self.end_headers()
        self.wfile.write(sig)
    

def main(args):
    if len(args) < 1 or (not os.path.exists(args[0])):
        logging.info("Usage: python3 sign_server.py [private key path]")
        return
    with open(args[0], 'r') as fp:
        global private_key
        private_key = ecdsa.SigningKey.from_pem(fp.read(), hashfunc=sha256)
    httpd = HTTPServer(('', 8080), SignatureHandler)
    logging.info("EEPROM Simple Signature Server Start")
    httpd.serve_forever()

if __name__ == "__main__":
    main(sys.argv[1:])