#!/bin/bash

# NecroHash Installer
# Installiert NecroHash und richtet den Autostart ein.

# Exit on error
set -e

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

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

# Determine script directory to find local files (requirements.txt etc)
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

echo "Installing NecroHash to $TARGET_DIR..."

# 1. Systemabhängigkeiten
echo "Installing system dependencies..."
apt-get update
# Add automake, autoconf, libtool explicitly, and ensure pthread support
# Added authbind for port 80 access as non-root
apt-get install -y python3 python3-venv git libncurses5-dev libudev-dev build-essential autoconf automake libtool pkg-config libcurl4-openssl-dev libusb-1.0-0-dev authbind

# 1.1 Configure authbind for Port 80
echo "Configuring authbind for Port 80..."
touch /etc/authbind/byport/80
chmod 500 /etc/authbind/byport/80
chown $USER /etc/authbind/byport/80

# 2. Cgminer Installation (Patched local version)
if [ ! -f "/usr/local/bin/cgminer" ] || [ "$1" == "--reinstall-cgminer" ]; then
    echo "Compiling and installing cgminer for Gridseed (Local Source)..."
    
    # Copy source to temp for building to keep repo clean
    cp -r "$SCRIPT_DIR/src/cgminer-gc3355" /tmp/cgminer-build
    cd /tmp/cgminer-build
    
    # Fix for modern GCC (10+) defaulting to -fno-common
    export CFLAGS="-fcommon -O2"
    
    if [ -f "./autogen.sh" ]; then
        ./autogen.sh
    else
        autoreconf -ivf
    fi
    
    # Explicitly link pthread if needed, though usually handled by configure
    # Enable scrypt AND gridseed. The patch in driver-gridseed.c ensures
    # that scrypt commands are only sent if --scrypt is active.
    ./configure --enable-gridseed --enable-scrypt --without-curses
    
    make
    make install
    cd ..
    rm -rf /tmp/cgminer-build
else
    echo "cgminer found, skipping compilation. Use --reinstall-cgminer to force."
fi

# 2.1 Setup USB Permissions (udev rules)
echo "Setting up USB permissions for Gridseed..."
# Gridseed usually uses STM32 Virtual COM Port (VID: 0483, PID: 5740)
# Adding rules for generic serial converters often used too.
cat <<EOF > /etc/udev/rules.d/10-gridseed.rules
SUBSYSTEM=="usb", ATTR{idVendor}=="0483", ATTR{idProduct}=="5740", MODE="0666", GROUP="plugdev"
SUBSYSTEM=="tty", ATTRS{idVendor}=="0483", ATTRS{idProduct}=="5740", MODE="0666", GROUP="plugdev"
EOF
udevadm control --reload-rules && udevadm trigger
usermod -a -G plugdev,dialout $USER
echo "User $USER added to plugdev/dialout groups."

# 3. NecroHash Dateien kopieren
if [ -d "$TARGET_DIR" ]; then
    echo "Backup existing installation..."
    mv "$TARGET_DIR" "${TARGET_DIR}_backup_$(date +%s)"
fi

echo "Copying NecroHash files from $SCRIPT_DIR..."
mkdir -p "$TARGET_DIR"
# Copy content from the repo directory where script is located
cp -r "$SCRIPT_DIR/"* "$TARGET_DIR/"
chown -R $USER:$USER "$TARGET_DIR"

# 4. Python Environment einrichten
echo "Setting up Python environment..."
# Use absolute path to requirements.txt
if [ -f "$TARGET_DIR/requirements.txt" ]; then
    su - $USER -c "cd $TARGET_DIR && python3 -m venv venv && source venv/bin/activate && pip install -r requirements.txt"
else
    echo "ERROR: requirements.txt not found in $TARGET_DIR"
    exit 1
fi

# 5. Systemd Services einrichten

# 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

# Mining 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
# Use wrapper script to handle mode switching (scrypt/sha256)
ExecStart=$TARGET_DIR/miner_wrapper.sh
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable necrohash-gui.service
systemctl enable necrohash-miner.service

echo "Installation complete."
echo "Edit config at $TARGET_DIR/cgminer.conf"
echo "Start services with:"
echo "  systemctl start necrohash-gui"
echo "  systemctl start necrohash-miner"
