#!/usr/bin/env bash

function print_help(){
	echo -e "hosts\t\tManages hosts in the yaml file"
	echo -e "\tlist\tLists hosts in the project"
	echo -e "\thosts_file\tUpdates the hosts file to reflect the hosts on this project"
	echo -e "\tip\tUses fzf to select an IP from the project"
	echo -e "\tadd\tAdd an IP address"
}

function listhosts(){
	local current="$(project current --path)"
	index="$current/index.yaml"
	if [ ! -f "$index" ]; then
		echo "No index file"
		exit 1
	fi
	if [ $(yq -r '.hosts | length ' "$index" ) -gt 0 ]; then
		yq -r '.hosts[] | [
			.ip,
			(if ( .domain | type == "array") then .domain | join(",") else .domain end),
			.description
		] | join(",")' "$index"
	else
		echo "No hosts in index file"
		exit 1
	fi
}

function get_hosts(){
	local current="$(project current --path)"
	index="$current/index.yaml"
	if [ ! -f "$index" ]; then
		echo ""
		exit 0
	fi
	if [ $(yq -r '.hosts | length ' "$index" ) -gt 0 ]; then
		yq -r '.hosts[]| select(.domain) | [
			.ip,
			(if ( .domain | type == "array") then .domain | join(",") else .domain end)
		] | join(",,")' "$index" | tr ',' '\t'
	else
		echo ""
		exit 0
	fi
}

function host_file(){
	sed '/# Project specific hosts/,$ d' /etc/hosts > /tmp/newhosts
	cat /tmp/newhosts > /etc/hosts
	rm /tmp/newhosts

	local current="$(project current --path)"
	if [ -n "$current" ]; then
		(
			echo "# Project specific hosts - Everything after this line will be deleted when the project is changed"
			get_hosts
		) >> /etc/hosts
	fi
}

function getip(){
	local current="$(project current --path)"
	index="$current/index.yaml"
	case "$1" in
		--fzf)
			ip=$( listhosts | fzf --no-preview | cut -d',' -f1)
			;;
		--dmenu)
			ip=$( listhosts | dmenu | cut -d',' -f1)
			echo "$ip" | xclip -selection primary
			echo "$ip" | xclip -selection clipboard
			;;
		--rofi)
			ip=$( listhosts | rofi -dmenu | cut -d',' -f1)
			echo "$ip" | xclip -selection primary
			echo "$ip" | xclip -selection clipboard
			;;
		*)
			ip=$( listhosts | fzf --no-preview | cut -d',' -f1)
			;;
	esac
	echo $ip
}

function addip(){
	local current="$(project current --path)"
	index="$current/index.yaml"
	echo -n "Domain: "
	read domain < /dev/tty
	echo -n "IP: "
	read ip < /dev/tty
	echo -n "Description: "
	read description < /dev/tty
	local host='{}'
	if [ -n "$domain" ]; then
		host="$(echo $host | jq ".domain=\"$domain\"" )"
	fi
	if [ -n "$ip" ]; then
		host="$(echo $host | jq ".ip=\"$ip\"" )"
	fi
	if [ -n "$description" ]; then
		host="$(echo $host | jq ".description=\"$description\"" )"
	fi
	echo $host
	yq --yaml-output ".hosts |= .+ [$host]" "$index" > newindex
	rm "$index"
	mv newindex "$index"
	host_file
}

case "$1" in 
	-h|--help)
		print_help | column -t -s"	"
		exit 0
		;;
	--parent-help)
		print_help
		exit 0
		;;
	list)
		listhosts
		;;
	hosts_file)
		shift
		host_file "$@"
		;;
	ip)
		getip
		;;
	add)
		addip
		;;
esac