#!/bin/bash

# NecroHash Updater
# Aktualisiert Code und Services OHNE Neukompilierung.

TARGET_DIR="/opt/necrohash"
USER="pi"

if [ "$EUID" -ne 0 ]; then
  echo "Bitte als root ausführen (sudo ./update.sh)"
  exit 1
fi

if [ ! -d "$TARGET_DIR" ]; then
    echo "Verzeichnis $TARGET_DIR nicht gefunden."
    exit 1
fi

cd "$TARGET_DIR"

echo "=== Stoppe Dienste ==="
systemctl stop necrohash-miner
systemctl stop necrohash-gui

echo "=== Aktualisiere Code (Git) ==="
# Lokale Änderungen (z.B. Config) kurzzeitig speichern
git stash
git pull origin master
# Lokale Änderungen wiederherstellen
git stash pop

echo "=== System-Konfiguration (Port 80 / Authbind) ==="
# Sicherstellen, dass authbind installiert ist
if ! command -v authbind &> /dev/null; then
    echo "Installiere authbind..."
    apt-get update && apt-get install -y authbind
fi

# Port 80 Freigabe
if [ ! -f "/etc/authbind/byport/80" ]; then
    echo "Konfiguriere Port 80 Zugriff..."
    touch /etc/authbind/byport/80
    chmod 500 /etc/authbind/byport/80
    chown $USER /etc/authbind/byport/80
fi

echo "=== Setze Berechtigungen ==="
chmod +x *.sh
chown -R $USER:$USER "$TARGET_DIR"

echo "=== Aktualisiere Service-Definitionen ==="
# Wir schreiben die Services neu, falls sich im Repo die Startlogik geändert hat

# Optional: Rebuild cgminer if requested
if [ "$1" == "--rebuild-miner" ]; then
    echo "=== Recompiling Miner from Local Source ==="
    # Reuse logic from install.sh essentially
    cp -r src/cgminer-gc3355 /tmp/cgminer-build
    cd /tmp/cgminer-build
    export CFLAGS="-fcommon -O2"
    ./autogen.sh
    ./configure --enable-gridseed --enable-scrypt --without-curses
    make -j1
    make install
    cd "$TARGET_DIR"
    rm -rf /tmp/cgminer-build
fi

# GUI Service
cat <<EOF > /etc/systemd/system/necrohash-gui.service
[Unit]
Description=NecroHash Web GUI
After=network.target

[Service]
User=$USER
WorkingDirectory=$TARGET_DIR
ExecStart=$TARGET_DIR/start_gui.sh
Restart=always

[Install]
WantedBy=multi-user.target
EOF

# Miner Service
cat <<EOF > /etc/systemd/system/necrohash-miner.service
[Unit]
Description=NecroHash Miner (cgminer)
After=network.target necrohash-gui.service

[Service]
User=$USER
WorkingDirectory=$TARGET_DIR
ExecStart=$TARGET_DIR/miner_wrapper.sh
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

echo "=== Starte Dienste neu ==="
systemctl daemon-reload
systemctl start necrohash-gui
systemctl start necrohash-miner

echo "Update abgeschlossen!"
