#!/usr/bin/env bash

#colors
MAGENTA=$(tput setaf 5)
CYAN=$(tput setaf 6)
YELLOW=$(tput setaf 3)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
NORMAL=$(tput sgr0)

BIN_DIR=$HOME/bin
YAMLDOC="$DOTFILES_DIR/info/tools.yml"
INSTALL_YES=${GREEN}✓${NORMAL}
INSTALL_NO=${RED}✗${NORMAL}

# get current binary files
shopt -s nullglob
BINARY_FILES=($HOME/bin/*)

alias eget="eget --system linux/amd64"

post_download_install() {

	tool=$1
	temp_file=$(mktemp -p . ${tool}.XXX.sh)
	key=$tool yq e 'explode(.) | .[env(key)].post-download' $YAMLDOC >$temp_file
	. $temp_file
	rm $temp_file

}

eget_tool() {

	tool=$1

	echo -n $tool

	user=$(key=$tool yq e 'explode(.) | .[env(key)].user' $YAMLDOC)
	asset=$(key=$tool yq e 'explode(.) | .[env(key)].asset // ""' $YAMLDOC)
	file=$(key=$tool yq e 'explode(.) | .[env(key)].file // ""' $YAMLDOC)
	to=$(key=$tool yq e 'explode(.) | .[env(key)].to // ""' $YAMLDOC)
	download_only=$(key=$tool yq e 'explode(.) | .[env(key)].download-only // ""' $YAMLDOC)

	eget $user/$tool \
		${asset:+--asset $asset} \
		${file:+--file $file} \
		${to:+--to $to} \
		${download_only:+--download-only} \
		-q

	if [[ $download_only ]]; then
		echo -n ' --> '
		echo -n 'running post-download script'
		post_download_install $tool
	fi

	echo
}

deps_check() {

	mkdir -p $BIN_DIR
	if ! $(is-executable eget); then
		echo "I don't see eget on your path..."
		read -p "Do you want to download it to ${BIN_DIR}? " -n 1 -r
		echo # (optional) move to a new line
		if [[ ! $REPLY =~ ^[Yy]$ ]]; then
			exit 1
		else
			curl https://zyedidia.github.io/eget.sh | sh
			mv eget $BIN_DIR/eget
		fi
	fi

	if ! $(is-executable yq); then
		eget mikefarah/yq --asset yq_linux_amd64
	fi

}

get_days() {
	install_date=$1
	date_out=$(date -d @$1 +'%Y.%m.%d %R')
	now=$(date +'%s')
	days=$(((now - install_date) / 86400))
	if ((days > 60)); then
		echo "${RED}$date_out${NORMAL}"
	elif ((days > 30)); then
		echo "${YELLOW}$date_out${NORMAL}"
	else
		echo "$date_out"
	fi
}

check_install() {
	bin_name=$BIN_DIR/$1
	if printf '%s\n' "${BINARY_FILES[@]}" | grep -Fxq "$bin_name"; then
		modified=$(date -r $bin_name +'%s')
		echo $(get_days $modified)
	fi
}

list() {

	deps_check

	user_len=$(yq e '.[] | .user ' $YAMLDOC | tail -n +2 | sort | uniq | awk '{print length}' | sort -nr | head -n 1)
	tool_len=$(yq e 'keys| .[]' $YAMLDOC | tail -n +2 | sort | uniq | awk '{print length}' | sort -nr | head -n 1)
	table_width=$(($user_len + $tool_len + 25))
	tool_cell=$(printf "%${tool_len}s" "")
	user_cell=$(printf "%${user_len}s" "")

	echo "${CYAN}CONFIGURED TOOLS${NORMAL}"
	printf "%${table_width}s\n" "" | tr ' ' =
	printf \
		"${CYAN}tool${NORMAL}%s | \
${CYAN}author${NORMAL}%s | \
${CYAN}  install date${NORMAL}\n" \
  "${tool_cell:4}" "${user_cell:6}"
	printf "%${table_width}s\n" "" | tr ' ' -
	readarray tools < <(yq e 'keys | .[]' $YAMLDOC)
	#sort tools for readability
	tools=($(echo "${tools[@]:1}" | tr ' ' '\n' | sort | uniq))
	for tool in "${tools[@]}"; do

		user=$(key=$tool yq e 'explode(.) | .[env(key)].user' $YAMLDOC)
		bin_name=$(key=$tool yq e 'explode(.) | .[env(key)].to' $YAMLDOC)
		[[ "$bin_name" == "null" ]] && bin_name=$tool

		modified=$(check_install $bin_name)

		! [[ -z "$modified" ]] && installed=$INSTALL_YES || installed=$INSTALL_NO

		printf \
			"${MAGENTA}%s${NORMAL}%s | \
${YELLOW}%s${NORMAL}%s | \
$installed $modified\n" \
			$tool "${tool_cell:${#tool}}" \
			$user "${user_cell:${#user}}"

	done

}

download() {
	if ! [ -z "$1" ]; then
		tool=$1

		echo "installing $tool"
		info=$(key=$tool yq e 'explode(.) | .[env(key)]' $YAMLDOC)
		if [[ $info == "null" ]]; then
			echo "$tool not found in $YAMLDOC"
			echo "exiting"
			exit 1
		else
			eget_tool $tool
		fi
	fi
}

download_all() {

	echo "Downloading binaries to ${GREEN}$BIN_DIR${NORMAL}"

	deps_check

	readarray tools < <(yq e 'keys | .[]' $YAMLDOC)
	echo "installing......"

	for tool in "${tools[@]:1}"; do
		eget_tool $tool
	done

}

help() {
	cat <<EOF

eget/yq powered binary downloader

usage: tools [tool tool2 ...]

optional flags:
  -h, --help  show this help text
  -l, --list  list all tools
  -a, --all   download all tools

EOF
}

for opt in "$@"; do
	case $opt in
	-h | --help)
		help
		exit 0
		;;
	-l | --list)
		list
		exit 0
		;;
	-a | --all)
		download_all
		exit 0
		;;
	-* | --*)
		echo "Invalid option: $opt"
		help
		exit 1
		;;
	*)
		args+=("$opt")
		shift
		;;
	esac
done

# if no args, show help

if [ -z "$args" ]; then
	echo "${RED}No arguments supplied${NORMAL}"
	help
	exit 0
else
	echo "Downloading binaries to ${GREEN}$BIN_DIR${NORMAL}"
	deps_check
	for tool in "$args"; do
		download $tool
	done
fi