#!/bin/bash

set -e -o pipefail

BASE=$(dirname "$(readlink -fm "$0")")
AML_FLASH_TOOL_DIR="$BASE/aml-flash-tool"
RK_FLASH_TOOL_DIR="$BASE/rk-flash-tool"
TB_FLASH_TOOL_DIR="$BASE/tone-dfu-tool"
AML_BURN_TOOL="$AML_FLASH_TOOL_DIR/aml-burn-tool"
RK_BURN_TOOL="$RK_FLASH_TOOL_DIR/rk-burn-tool"
TB_BURN_TOOL="$TB_FLASH_TOOL_DIR/tone-burn-tool"
KHADAS_BURN_TOOL="$BASE/burn-tool"
INSTALL_DIR="/usr/local/bin"

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}')


RED='\033[0;31m'
RESET='\033[m'

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

setup_ubuntu_host() {
	local hostdeps="libusb-dev git parted lib32z1 lib32stdc++6 libusb-0.1-4 libusb-1.0-0-dev libusb-1.0-0 ccache libncurses5 pv base-files linux-base xz-utils"
	local deps=()
	local installed=$(dpkg-query -W -f '${db:Status-Abbrev}|${binary:Package}\n' '*' 2>/dev/null | grep '^ii' | awk -F '|' '{print $2}' | cut -d ':' -f 1)

	if [[ "$DISTRIB" == "Ubuntu" ]] && [[ "$DISTRIB_RELEASE" == "18.10" || "$DISTRIB_RELEASE" =~ "20" || "$DISTRIB_RELEASE" =~ "22" ]]; then
		hostdeps="$hostdeps lib32ncurses6"
	else
		hostdeps="$hostdeps lib32ncurses5"
	fi

	for packet in $hostdeps; do
		if ! grep -q -x -e "$packet" <<< "$installed"; then deps+=("$packet"); fi
	done

	if [[ ${#deps[@]} -gt 0 ]]; then
		echo "Installing dependencies"
		echo "Requires root privileges, please enter your passowrd!"
		sudo apt update
		sudo apt -y --no-install-recommends install "${deps[@]}"
		sudo update-ccache-symlinks
	fi
}

setup_arch_host() {
	local hostdeps=("libusb" "git" "parted" "lib32-zlib" "libusb-compat" "usbutils" "ccache" "pv" "file" "base" "xz")
	local aur_packages="ncurses5-compat-libs lib32-ncurses5-compat-libs"
	echo "Installing dependencies"
	echo "Requires root privileges, please enter your passowrd!"
	# Install dependencies
	sudo pacman -Syyu --noconfirm --needed "${hostdeps[@]}"
	# Install AUR packages
	for package in $aur_packages; do
		echo "Installing $package"
		git clone https://aur.archlinux.org/"$package"
		cd "$package" || exit
		makepkg -si --skippgpcheck --noconfirm --needed
		cd - || exit
		rm -rf "$package"
	done
	sudo update-ccache-symlinks
}

prepare_host() {
	case $DISTRIB in
	    "\"Arch\"")
	    setup_arch_host
		;;
	    "\"Ubuntu\"")
	    setup_ubuntu_host
		;;
		*)
		echo "$DISTRIB is unsupported"
	esac
}

prepare_host

echo -e "Installing Amlogic flash-tool..."
$AML_FLASH_TOOL_DIR/INSTALL
echo -e "\nInstalling Rockchip flash-tool..."
$RK_FLASH_TOOL_DIR/INSTALL
echo -e "\nInstalling Tone burn-tool..."
$TB_FLASH_TOOL_DIR/INSTALL
echo -e "Installing Khadas burn-tool..."
mkdir -p $INSTALL_DIR
sudo ln -fs $KHADAS_BURN_TOOL $INSTALL_DIR/$(basename $KHADAS_BURN_TOOL)

echo "Done!"
