#!/bin/bash

set -e -o pipefail

BASE=$(dirname "$(readlink -fm "$0")")
KHADAS_TOOL="$BASE/tone-burn-tool"
RULES_DIR="$BASE/rules"
DISTRIB=$(cat /etc/lsb-release | grep "DISTRIB_ID" | awk -F "=" '{print $2}')
DISTRIB_RELEASE=$(cat /etc/lsb-release | grep "DISTRIB_RELEASE" | awk -F "=" '{print $2}')
INSTALL_DIR="/usr/local/bin"

RULE=

RED='\033[0;31m'
YELLOW="\e[0;33m"
RESET='\033[m'

echo ""
echo "==============================================="
echo ""
echo "Host PC: $DISTRIB $DISTRIB_RELEASE"
echo ""
echo "==============================================="
echo ""

error_msg() {
	echo -e ${RED}Error:${RESET} $1
}

warning_msg() {
	echo -e ${YELLOW}Warning:${RESET} $1
}

if [ "$DISTRIB" != "Ubuntu" ]; then
	warning_msg "This burn tool just support Ubuntu now, other distributions haven't been verified!"
	read -p "Continue any way? [No/yes] " answer
	if [[ "$answer" != "yes" && "$answer" != "Yes" ]]; then
		exit 1
	else
		IGNORE_CHECK=yes
		warning_msg "You choose to not check the system environment, the installation may be failed!!!"
	fi
fi

echo "Installing USB rules..."

if [[ "$IGNORE_CHECK" == "yes" || "$DISTRIB_RELEASE" =~ "16" || "$DISTRIB_RELEASE" =~ "18" || "$DISTRIB_RELEASE" =~ "20" || "$DISTRIB_RELEASE" =~ "22" ]]; then
	RULE="$RULES_DIR/80-tone-usb.rules"
	sudo cp $RULE /etc/udev/rules.d
else
	error_msg "Ubuntu $DISTRIB_RELEASE haven't been verified!"
	exit 1
fi

sudo udevadm control --reload-rules

echo "Installing tone-burn-tool..."
mkdir -p $INSTALL_DIR
sudo ln -fs $KHADAS_TOOL $INSTALL_DIR/$(basename $KHADAS_TOOL)

echo "Done!"
