#!/bin/bash
# Names of packages under different distros
PACKAGES_DEBIAN="uhd-host"
PACKAGES_RHEL="uhd-tools uhd-devel uhd soapy-uhd"
if [[ $EUID -ne 0 ]]; then
	echo "Error: This script must be run as root. Exiting." >&2
	exit 1
fi


# Function to determine the Linux distribution
detect_distro() {
    if [[ -f /etc/os-release ]]; then
        . /etc/os-release
        DISTRO_ID=$ID
    elif command -v lsb_release >/dev/null 2>&1; then
        DISTRO_ID=$(lsb_release -si | tr '[:upper:]' '[:lower:]')
    elif [[ -f /etc/debian_version ]]; then
        DISTRO_ID="debian"
    elif [[ -f /etc/fedora-release ]]; then
        DISTRO_ID="fedora"
    else
        DISTRO_ID="unknown"
    fi

    echo "$DISTRO_ID"
}


# Check distro version to install correct packages
DISTRO_ID=$(detect_distro)
case "$DISTRO_ID" in 
	debian|ubuntu|pop|linuxmint|elementary|kali)
		apt install -y $PACKAGES_DEBIAN
		;;

	fedora|rhel|centos)
		yum install -y $PACKAGES_RHEL
		;;
esac


# Ensuring Environment variables
#export UHD_IMAGES_DIR=/usr/lib/ettus/ # User specific alternative
echo "UHD_IMAGES_DIR=/usr/lib/ettus/" >> /etc/environment # Ensure env across multiple installs on multiple users.
echo "UHD_IMAGES_DIR=/usr/lib/ettus/" >> ~/.bashrc
source /etc/environment
export UHD_IMAGES_DIR=/usr/lib/ettus/

# Copying Firmware files
mkdir /usr/lib/ettus/ # Create the library folder
cp -r ./firmware/* /usr/lib/ettus/ # Copy firmware files
chown -R root:root /usr/lib/ettus/ # Ensure root owns the files
chmod 776 -R /usr/lib/ettus/ # This makes only root able to change the folder and file content

uhd_find_devices # Needs to identify before it flashes
uhd_image_loader --download --args type=b200 # Flashes from the directory the file is in.