import os
import subprocess
import hmac
import hashlib
import json
from flask import Flask, request, jsonify

app = Flask(__name__)

WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "change-me")
DEPLOY_SCRIPT = os.environ.get("DEPLOY_SCRIPT", "/opt/aufmassweb/deploy.sh")

def verify_signature(payload, signature):
    if not signature:
        return False
    expected = "sha256=" + hmac.new(WEBHOOK_SECRET.encode(), payload, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)

@app.route("/webhook", methods=["POST"])
def webhook():
    signature = request.headers.get("X-Gitea-Signature", "")
    payload = request.get_data()

    if not verify_signature(payload, signature):
        return jsonify({"error": "invalid signature"}), 403

    data = request.get_json(silent=True) or {}
    ref = data.get("ref", "")
    if ref != "refs/heads/main":
        return jsonify({"message": f"ignored push to {ref}"}), 200

    result = subprocess.run(
        ["bash", DEPLOY_SCRIPT],
        capture_output=True, text=True, timeout=300
    )

    return jsonify({
        "status": "ok" if result.returncode == 0 else "error",
        "stdout": result.stdout,
        "stderr": result.stderr,
    }), (200 if result.returncode == 0 else 500)

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

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5001)
