#!/bin/bash
#
# zfsdu Installation Script - Build from Source
# For Debian/Ubuntu/Proxmox
#
# Use install-binary.sh if you already have the binary
#

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo -e "${GREEN}================================${NC}"
echo -e "${GREEN}  zfsdu - Build from Source     ${NC}"
echo -e "${GREEN}================================${NC}"
echo

# Check root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}Error: Please run as root${NC}"
    exit 1
fi

# Detect OS
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$ID
fi

echo -e "${YELLOW}Installing build dependencies...${NC}"
apt-get update
apt-get install -y curl build-essential pkg-config

# Install Rust if needed
if ! command -v cargo &> /dev/null; then
    echo -e "${YELLOW}Installing Rust...${NC}"
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
    source "$HOME/.cargo/env"
fi

export PATH="$HOME/.cargo/bin:$PATH"

# Build
echo -e "${YELLOW}Building zfsdu...${NC}"
cd "$SCRIPT_DIR"
cargo build --release

# Install
echo -e "${YELLOW}Installing...${NC}"
cp "$SCRIPT_DIR/target/release/zfsdu" /usr/local/bin/
chmod +x /usr/local/bin/zfsdu

echo
echo -e "${GREEN}Done! Run 'zfsdu' to start.${NC}"
