#!/bin/bash

set -e  # Exit on error


SCRIPT_DEVICE_ID=""

print_usage() {
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  --device-id ID    Set the device ID (default: DEVICE_ID env var or auto-generated)"
    echo "  -h, --help        Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 --device-id my-device-001"
    echo "  DEVICE_ID=my-pi $0"
    echo "  $0  # Interactive mode with defaults"
}

while [[ $# -gt 0 ]]; do
    case $1 in
        --device-id)
            SCRIPT_DEVICE_ID="$2"
            shift 2
            ;;
        -h|--help)
            print_usage
            exit 0
            ;;
        *)
            echo "Error: Unknown option: $1"
            print_usage
            exit 1
            ;;
    esac
done


# Default device ID: use --device-id arg, then DEVICE_ID env var, then hostname, then MAC
if [ -n "$SCRIPT_DEVICE_ID" ]; then
    DEVICE_ID="$SCRIPT_DEVICE_ID"
elif [ -n "${DEVICE_ID:-}" ]; then
    DEVICE_ID="${DEVICE_ID}"
else
    # Try to get a meaningful default from hostname
    HOSTNAME=$(hostname)
    if [[ "$HOSTNAME" == "raspberrypi" || -z "$HOSTNAME" ]]; then
        # Generic hostname, generate from MAC address of first interface
        MAC=$(cat /sys/class/net/$(ip route show default | awk '/default/ {print $5}')/address 2>/dev/null | tr -d ':' | tail -c 7)
        DEVICE_ID="pi-${MAC:-unknown}"
    else
        DEVICE_ID="$HOSTNAME"
    fi
fi


echo "=================================="
echo "OMGrab SDK Installation"
echo "=================================="
echo ""
echo "Please confirm these settings:"
echo ""
echo "  Device ID:    $DEVICE_ID"
echo "  Build:        Local (from current directory)"
echo ""
echo "=================================="
echo ""
read -p "Continue with these settings? [y/N] " -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Installation cancelled."
    echo ""
    echo "To customize, run with arguments:"
    echo "  $0 --device-id YOUR_ID"
    exit 1
fi

echo ""
echo "Starting installation..."
echo ""


# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo "Error: This script must be run as root (use sudo)"
    exit 1
fi

# Verify ARM64 architecture (OMGrab streaming device)
ARCH=$(uname -m)
if [ "$ARCH" != "aarch64" ] && [ "$ARCH" != "arm64" ]; then
    echo "Error: This installer requires ARM64 architecture"
    echo "Detected architecture: $ARCH"
    exit 1
fi

echo "Step 1: Checking required tools..."
# Install curl if not present (needed for Docker install)
if ! command -v curl &> /dev/null; then
    echo "curl not found. Installing curl..."
    apt-get update -qq
    apt-get install -y curl
    echo "curl installed successfully."
else
    echo "curl already installed."
fi

echo "Step 2: Checking Docker installation..."
if ! command -v docker &> /dev/null; then
    echo "Docker not found. Installing Docker..."
    curl -fsSL https://get.docker.com -o get-docker.sh
    sh get-docker.sh
    rm get-docker.sh

    if [ "$SUDO_USER" != "" ]; then
        usermod -aG docker "$SUDO_USER"
        echo "Added $SUDO_USER to docker group. You may need to log out and back in for this to take effect."
    fi

    systemctl start docker
    systemctl enable docker

    echo "Docker installed successfully."
else
    echo "Docker already installed: $(docker --version)"
fi

# Verify docker compose is available
if ! docker compose version &> /dev/null; then
    echo "docker compose not found. Installing docker-compose-plugin..."
    apt-get update -qq
    apt-get install -y docker-compose-plugin
    echo "docker-compose-plugin installed successfully."
fi
echo "Docker Compose found: $(docker compose version)"

# Get the project root (one level up from setup/)
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )"
INSTALL_DIR="/opt/omgrab"
SERVICE_FILE="omgrab.service"

echo "Step 3: Creating installation directory..."
mkdir -p "$INSTALL_DIR"
mkdir -p "$INSTALL_DIR/data"

echo "Step 4: Copying docker-compose.yml and wifi-connect..."
cp "$SCRIPT_DIR/docker-compose.yml" "$INSTALL_DIR/"
rsync -a --delete "$SCRIPT_DIR/wifi-connect/" "$INSTALL_DIR/wifi-connect/"

echo "Step 5: Creating .env file with device configuration..."
cat > "$INSTALL_DIR/.env" << EOF
# OMGrab Configuration
# Generated by install.sh on $(date -u +%Y-%m-%dT%H:%M:%SZ)

DEVICE_ID=$DEVICE_ID

# Local build version marker
AGENT_VERSION=local-build
EOF

echo ".env file created:"
cat "$INSTALL_DIR/.env"

echo "Step 6: Setting correct permissions..."
chown -R root:root "$INSTALL_DIR"
chmod -R 755 "$INSTALL_DIR"
chmod -R 777 "$INSTALL_DIR/data"  # Docker container needs write access

echo "Step 7: Configuring persistent journald logging..."
mkdir -p /var/log/journal
mkdir -p /etc/systemd/journald.conf.d
cat > /etc/systemd/journald.conf.d/omgrab.conf << 'JOURNALD_EOF'
[Journal]
Storage=persistent
SyncIntervalSec=30s
SystemMaxUse=200M
JOURNALD_EOF
systemctl restart systemd-journald
echo "Persistent journald logging configured."

echo "Step 7a: Installing early-led boot indicator..."
cp "$SCRIPT_DIR/service/early-led.sh" "$INSTALL_DIR/early-led.sh"
chmod +x "$INSTALL_DIR/early-led.sh"
cp "$SCRIPT_DIR/service/early-led.service" "/etc/systemd/system/early-led.service"
chmod 644 "/etc/systemd/system/early-led.service"

echo "Step 7b: Enabling I2C interface..."
# Required for battery monitor (INA219 over /dev/i2c-1).
raspi-config nonint do_i2c 0
modprobe i2c-dev
echo "I2C interface enabled."

echo "Step 8: Installing systemd service..."
cp "$SCRIPT_DIR/service/$SERVICE_FILE" "/etc/systemd/system/$SERVICE_FILE"
chmod 644 "/etc/systemd/system/$SERVICE_FILE"

echo "Step 8a: Installing WiFi stability fixes..."
cp "$SCRIPT_DIR/service/wifi-stable.conf" "/etc/NetworkManager/conf.d/wifi-stable.conf"
chmod 644 "/etc/NetworkManager/conf.d/wifi-stable.conf"
cp "$SCRIPT_DIR/service/99-wifi-stable.sh" "/etc/NetworkManager/dispatcher.d/99-wifi-stable"
chown root:root "/etc/NetworkManager/dispatcher.d/99-wifi-stable"
chmod 755 "/etc/NetworkManager/dispatcher.d/99-wifi-stable"
if systemctl is-enabled wifi-powersave-off.service 2>/dev/null; then
    systemctl disable wifi-powersave-off.service 2>/dev/null || true
    rm -f /etc/systemd/system/wifi-powersave-off.service
fi

echo "Step 9: Reloading systemd daemon..."
systemctl daemon-reload

echo "Step 10: Enabling early-led service..."
systemctl enable early-led.service

echo "Step 10a: WiFi stability script installed (NM dispatcher, no service needed)."

echo "Step 10b: Setting up Samba file share..."
if ! command -v smbd &> /dev/null; then
    apt-get update -qq
    apt-get install -y samba
fi
mkdir -p /etc/samba/smb.conf.d
# Enable guest access in global config if not already set
if ! grep -q 'map to guest' /etc/samba/smb.conf 2>/dev/null; then
    sed -i '/^\[global\]/a\\   map to guest = Bad User' /etc/samba/smb.conf
fi
# Add include for our share config in the [global] section
if ! grep -q 'include = /etc/samba/smb.conf.d/omgrab.conf' /etc/samba/smb.conf 2>/dev/null; then
    sed -i '/^\[global\]/a\\   include = /etc/samba/smb.conf.d/omgrab.conf' /etc/samba/smb.conf
fi
SAMBA_OUTPUT_DIR="$INSTALL_DIR/data/spool/output"
mkdir -p "$SAMBA_OUTPUT_DIR"
sed "s|SPOOL_OUTPUT_PATH|$SAMBA_OUTPUT_DIR|" "$SCRIPT_DIR/service/smb-omgrab.conf" \
    > /etc/samba/smb.conf.d/omgrab.conf
# Create the omgrab Samba user if it doesn't exist
if ! pdbedit -L 2>/dev/null | grep -q '^omgrab:'; then
    id omgrab &>/dev/null || useradd -r -s /usr/sbin/nologin omgrab
    printf 'omgrab\nomgrab\n' | smbpasswd -a omgrab -s
    smbpasswd -e omgrab
fi
systemctl enable smbd
systemctl restart smbd
echo "Samba share configured: smb://$(hostname).local/omgrab"

echo "Step 11: Cleaning up any old containers..."
docker rm -f omgrab-runtime wifi-connect 2>/dev/null || true
# Clean up legacy container name from older installs
docker rm -f pi-agent 2>/dev/null || true

echo "Step 12: Building Docker image from local code..."
cd "$SCRIPT_DIR"
docker compose --env-file "$INSTALL_DIR/.env" --profile wifi-setup build

echo "Step 12a: Copying compose file and wifi-connect build context to install directory..."
cp "$SCRIPT_DIR/docker-compose.yml" "$INSTALL_DIR/"
rsync -a --delete "$SCRIPT_DIR/wifi-connect/" "$INSTALL_DIR/wifi-connect/"

echo "Step 13: Checking if service is already running..."
if systemctl is-active --quiet "$SERVICE_FILE" 2>/dev/null; then
    echo "Service is running. Restarting to apply changes..."
    systemctl restart "$SERVICE_FILE"
    echo "Service restarted successfully."
else
    echo "Enabling service to start on boot..."
    systemctl enable "$SERVICE_FILE"
    echo "Service enabled."
fi

echo ""
echo "=================================="
echo "Installation Complete!"
echo "=================================="
echo ""
echo "Configuration:"
echo "  Device ID:    $DEVICE_ID"
echo ""
echo "Useful commands:"
echo "  Start service:   sudo systemctl start omgrab"
echo "  Stop service:    sudo systemctl stop omgrab"
echo "  Check status:    sudo systemctl status omgrab"
echo "  View logs:       sudo journalctl -u omgrab -f"
echo "  Previous boot:   sudo journalctl -u omgrab --boot=-1"
echo "  List boots:      journalctl --list-boots"
echo "  Docker logs:     docker compose -f /opt/omgrab/docker-compose.yml logs -f"
echo ""
echo "To reconfigure, edit /opt/omgrab/.env or re-run this installer."
echo ""
read -p "Start the service now? [Y/n] " -r
echo ""

if [[ ! $REPLY =~ ^[Nn]$ ]]; then
    echo "Starting omgrab service..."
    systemctl start "$SERVICE_FILE"
    echo ""
    echo "Service started! Checking status..."
    sleep 2
    systemctl status "$SERVICE_FILE" --no-pager
fi
