#!/bin/sh
set -e

if [ "$1" = "1" ] || [ "$1" = "2" ]; then
    DATA_DIR="/var/lib/vyoma"
    BIN_DIR="${DATA_DIR}/bin"

    # Add installing user to vyoma and kvm groups
    if [ -n "$SUDO_USER" ]; then
        usermod -aG vyoma "$SUDO_USER" 2>/dev/null || true
        usermod -aG kvm "$SUDO_USER" 2>/dev/null || true
        echo "Added $SUDO_USER to vyoma and kvm groups. Log out and back in to use CLI."
    fi

    # Fix /dev/kvm permissions
    chmod 0660 /dev/kvm 2>/dev/null || true
    chown root:kvm /dev/kvm 2>/dev/null || true

    # Create runtime directory
    mkdir -p /run/vyoma
    chown root:vyoma /run/vyoma 2>/dev/null || true
    chmod 0775 /run/vyoma 2>/dev/null || true

    # Setup CNI plugins directory symlink
    mkdir -p /var/lib/vyoma/.vyoma/cni 2>/dev/null || true
    rm -rf /var/lib/vyoma/.vyoma/cni/bin 2>/dev/null || true
    ln -sf /usr/lib/vyoma/cni/bin /var/lib/vyoma/.vyoma/cni/bin 2>/dev/null || true

    # Ensure directories exist and have proper permissions
    mkdir -p "${BIN_DIR}"
    chown -R vyoma:vyoma "${DATA_DIR}"
    chmod 755 "${DATA_DIR}"
    chmod 755 "${BIN_DIR}"
    
    if [ -f "${BIN_DIR}/cloud-hypervisor" ]; then
        chmod +x "${BIN_DIR}/cloud-hypervisor"
    fi
    
    if [ -f "${BIN_DIR}/vyoma-agent-vm" ]; then
        chmod +x "${BIN_DIR}/vyoma-agent-vm"
    fi

    # Create vyoma0 bridge if it doesn't exist
    if ! ip link show vyoma0 > /dev/null 2>&1; then
        ip link add name vyoma0 type bridge
        ip addr add 172.16.0.1/24 dev vyoma0 || true
        ip link set dev vyoma0 up
    fi

    # Reload systemd and enable/start the service
    systemctl daemon-reload || true
    systemctl enable vyomad.service || true
    
    if [ "$1" = "1" ]; then
        systemctl start vyomad.service || true
    else
        systemctl try-restart vyomad.service || true
    fi

    if systemctl is-active --quiet vyomad.service; then
        echo "vyomad daemon is running."
    else
        echo "Notice: vyomad.service is not active yet. Check 'systemctl status vyomad' or verify /dev/kvm permissions."
    fi

    echo "Vyoma v3.1.0 installed successfully!"
    echo "Open http://localhost:8080 for the dashboard"
    echo "Run 'vyoma run nginx:latest' to start your first VM"
fi
exit 0
