"""
Honor FRP Tool - cPanel Python Bridge
======================================
Deploy this on cPanel as a Python Flask app.
Place platform-tools in the same folder.

Folder structure on cPanel:
  public_html/frp/
    passenger_wsgi.py   ← cPanel entry point
    frp_bridge.py       ← this file
    platform-tools/
      fastboot
      adb

Install deps via cPanel Terminal:
  pip install flask flask-cors
"""

import subprocess, os, sys, json
from flask import Flask, jsonify, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

# ── Platform-tools path (same folder as this script) ──────────────
BASE_DIR      = os.path.dirname(os.path.abspath(__file__))
PLATFORM_DIR  = os.path.join(BASE_DIR, 'platform-tools')
FASTBOOT      = os.path.join(PLATFORM_DIR, 'fastboot')
ADB           = os.path.join(PLATFORM_DIR, 'adb')

# Make sure fastboot/adb are executable
for bin_path in [FASTBOOT, ADB]:
    if os.path.isfile(bin_path):
        os.chmod(bin_path, 0o755)

# ── Helper ────────────────────────────────────────────────────────
def run(cmd, timeout=8):
    try:
        r = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
        out = r.stdout.decode('utf-8', errors='ignore').strip()
        err = r.stderr.decode('utf-8', errors='ignore').strip()
        return out or err
    except subprocess.TimeoutExpired:
        return ''
    except Exception as e:
        return ''

def fb(args, timeout=8):
    return run([FASTBOOT] + args, timeout)

def fb_var(var):
    raw = fb(['getvar', var])
    for line in raw.splitlines():
        if var in line and ':' in line:
            return line.split(':', 1)[1].strip()
    return ''

def adb_cmd(args, timeout=8):
    return run([ADB] + args, timeout)

# ── Routes ────────────────────────────────────────────────────────

@app.route('/')
def index():
    return jsonify({'tool': 'Honor FRP Bridge', 'version': '2.0', 'status': 'online'})

@app.route('/status')
def status():
    fb_exists = os.path.isfile(FASTBOOT)
    return jsonify({
        'status':          'ok',
        'fastboot_found':  fb_exists,
        'fastboot_path':   FASTBOOT,
        'platform_dir':    PLATFORM_DIR,
    })

@app.route('/scan')
def scan():
    raw = fb(['devices'])
    if not raw:
        return jsonify({'found': False, 'error': 'fastboot not found or not executable'})
    lines = [l for l in raw.splitlines() if 'fastboot' in l.lower() and l.strip()]
    if not lines:
        return jsonify({'found': False, 'error': 'No fastboot device connected'})
    device_id = lines[0].split()[0]
    return jsonify({'found': True, 'device_id': device_id, 'count': len(lines)})

@app.route('/read')
def read_device():
    scan_data = scan().get_json()
    if not scan_data.get('found'):
        return jsonify({'success': False, 'error': scan_data.get('error', 'No device')}), 404

    sn         = fb_var('serialno')
    product    = fb_var('product')
    model      = fb_var('model') or fb_var('hw-revision')
    bootloader = fb_var('version-bootloader')
    baseband   = fb_var('version-baseband')
    unlocked   = fb_var('unlocked')
    secure     = fb_var('secure')
    battery    = fb_var('battery-voltage')
    imei1      = fb_var('imei')
    imei2      = fb_var('imei2')
    brand      = fb_var('variant') or 'HUAWEI/HONOR'

    if not sn:
        sn = adb_cmd(['get-serialno']) or ''

    return jsonify({
        'success':    True,
        'sn':         sn         or 'N/A',
        'product':    product    or 'N/A',
        'brand':      brand,
        'model':      model      or 'N/A',
        'bootloader': bootloader or 'N/A',
        'baseband':   baseband   or 'N/A',
        'unlocked':   unlocked   or 'N/A',
        'secure':     secure     or 'N/A',
        'battery':    battery    or 'N/A',
        'imei1':      imei1      or 'N/A',
        'imei2':      imei2      or 'N/A',
    })

@app.route('/reboot')
def reboot():
    result = fb(['reboot'])
    return jsonify({'success': bool(result), 'message': 'Rebooting to normal mode...'})

if __name__ == '__main__':
    print("Honor FRP Bridge running on http://0.0.0.0:5000")
    app.run(host='0.0.0.0', port=5000, debug=False)
