#!/bin/bash

set -e -o pipefail

BASE=$(dirname "$(readlink -fm "$0")")
FLASH_TOOL="$BASE/flash-tool"
KHADAS_TOOL="$BASE/aml-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 flash 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 [[ "$DISTRIB_RELEASE" =~ "12" ]]; then
	RULE="$RULES_DIR/70-persistent-usb-ubuntu12.rules"
	sudo cp $RULE /etc/udev/rules.d
	sudo sed -i s/OWNER=\"amlogic\"/OWNER=\"`whoami`\"/g /etc/udev/rules.d/$(basename $RULE)
elif [[ "$IGNORE_CHECK" == "yes" || "$DISTRIB_RELEASE" =~ "14" || "$DISTRIB_RELEASE" =~ "16" || "$DISTRIB_RELEASE" =~ "18" || "$DISTRIB_RELEASE" =~ "19" || "$DISTRIB_RELEASE" =~ "20" || "$DISTRIB_RELEASE" =~ "22" ]]; then
	RULE="$RULES_DIR/70-persistent-usb-ubuntu14.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 flash-tool..."
mkdir -p $INSTALL_DIR
sudo ln -fs $KHADAS_TOOL $INSTALL_DIR/$(basename $KHADAS_TOOL)

echo "Done!"
