from flask import request
import subprocess
from flask import Flask, jsonify
from datetime import datetime

app = Flask(__name__)

def execute_command(cmd):
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
        return {'success': result.returncode == 0, 'stdout': result.stdout, 'stderr': result.stderr}
    except Exception as e:
        return {'success': False, 'error': str(e)}
@app.before_request
def before_request():
    current_time = datetime.now().isoformat()
    print(f"Request: {request.method} {request.path} {current_time}")

@app.route('/health', methods=['GET'])
def health_check():
    return jsonify({'status': 'healthy'})

@app.route('/nginx/reload', methods=['POST', 'GET'])
def reload_nginx():
    result = execute_command(['/usr/local/nginx/sbin/nginx', '-s', 'reload'])
    if result['success']:
        return jsonify({'success': True, 'message': 'Nginx 重启成功',})
    else:
        return jsonify({'success': False, 'error': 'Nginx 重启失败', 'details': result.get('error') or result.get('stderr', '')}), 500

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5020, debug=False)
    
    
'''
acme.sh --install-cert -d www.xtleto.cn \
    --cert-file /ce/www.xtleto.cn/cert.pem \
    --key-file /ce/www.xtleto.cn/key.pem \
    --fullchain-file /ce/www.xtleto.cn/fullchain.pem \
    --reloadcmd "curl -s -X GET http://127.0.0.1:5031/nginx/reload"
'''