import http.server
import json
import subprocess
import os

PORT = 5005
BACKUP_FILE = '/var/www/app_update/easybook/cloud_backup.json'

class Handler(http.server.BaseHTTPRequestHandler):
    def _send_json(self, data, code=200):
        body = json.dumps(data, ensure_ascii=False).encode('utf-8')
        self.send_response(code)
        self.send_header('Content-Type', 'application/json; charset=utf-8')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.send_header('Content-Length', str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()

    def do_GET(self):
        req_path = self.path.split('?')[0]
        if req_path == '/api/vps/info':
            try:
                uptime = subprocess.check_output('uptime', shell=True, text=True).strip()
                mem = subprocess.check_output('free -m', shell=True, text=True).strip()
                disk = subprocess.check_output('df -h /', shell=True, text=True).strip()
                self._send_json({
                    'status': 'online',
                    'ip': '152.32.144.194',
                    'uptime': uptime,
                    'memory': mem,
                    'disk': disk
                })
            except Exception as e:
                self._send_json({'status': 'error', 'message': str(e)}, 500)
        elif req_path == '/api/backup/download':
            if os.path.exists(BACKUP_FILE):
                try:
                    with open(BACKUP_FILE, 'r', encoding='utf-8') as f:
                        data = json.load(f)
                    self._send_json({'code': 200, 'data': data})
                except Exception as e:
                    self._send_json({'code': 500, 'msg': str(e)}, 500)
            else:
                self._send_json({'code': 404, 'msg': 'VPS云端暂无备份文件'}, 404)
        else:
            self._send_json({'error': 'Not found'}, 404)

    def do_POST(self):
        req_path = self.path.split('?')[0]
        if req_path == '/api/backup/upload':
            try:
                length = int(self.headers.get('Content-Length', 0))
                body = self.rfile.read(length).decode('utf-8')
                data = json.loads(body)
                with open(BACKUP_FILE, 'w', encoding='utf-8') as f:
                    json.dump(data, f, ensure_ascii=False, indent=2)
                self._send_json({'code': 200, 'msg': '云端备份成功！'})
            except Exception as e:
                self._send_json({'code': 500, 'msg': str(e)}, 500)
        else:
            self._send_json({'error': 'Not found'}, 404)

if __name__ == '__main__':
    with http.server.ThreadingHTTPServer(('0.0.0.0', PORT), Handler) as httpd:
        httpd.serve_forever()
