#!/bin/bash
BASE=/home/matthiasberner/Schreibtisch/kodi/xstreamDownloader

# 1. Replace tools.py with fixed version
cp "$BASE/xstream/resources/lib/_tools_fixed.py" "$BASE/xstream/resources/lib/tools.py"

# 2. Fix requestHandler.py - guard sUrl
python3 -c "
with open('$BASE/xstream/resources/lib/handler/requestHandler.py') as f:
    c = f.read()
old = '        self._sUrl = self.__cleanupUrl(sUrl)'
new = '        if not isinstance(sUrl, str): sUrl = \"\"\n        self._sUrl = self.__cleanupUrl(sUrl)'
if old in c and 'not isinstance' not in c:
    c = c.replace(old, new)
    with open('$BASE/xstream/resources/lib/handler/requestHandler.py', 'w') as f:
        f.write(c)
    print('requestHandler fixed')
else:
    print('requestHandler already fixed')
"

# 3. mini_app.py wurde am 6.7.2026 gelöscht — app.py ist der aktive Server

# 4. Kill old server, start new
fuser -k 8765/tcp 2>/dev/null
sleep 1
cd "$BASE"
python3 app.py > /tmp/server.log 2>&1 &
SERVER_PID=$!
sleep 3

# 5. Test
echo "=== Server PID: $SERVER_PID ==="
curl -s http://127.0.0.1:8765/api/sites | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'Sites OK: {len(d)} sites')" 2>&1
curl -s http://127.0.0.1:8765/api/sites/hdfilme/entries | python3 -c "import sys,json; d=json.load(sys.stdin); print(f'Entries: {len(d)}')" 2>&1
echo "=== Log tail ==="
tail -5 /tmp/server.log
