#!/bin/bash

# SSH into a device with credentials from ports.conf

# Source hardware configuration reader
source "/usr/share/rpi-power-hat/scripts/hardware-reader.sh"

# Configuration file path
# Use installed config file by default, fall back to development config
if [ -f "/etc/rpi-power-hat/ports.conf" ]; then
	CONFIG_FILE="/etc/rpi-power-hat/ports.conf"
else
	echo "Error: Could not find ports.conf configuration file" >&2
	exit 1
fi

print_usage() {
	echo "SSH connection tool for rpi-power-hat devices"
	echo "Usage: rpi-power-hat ssh <port> [command]" 
	echo
	echo "Available ports: B1, B2, T1, T2"
	echo
	echo "Examples:"
	echo "  rpi-power-hat ssh B1    # SSH into device on port B1"
	echo "  rpi-power-hat ssh T2    # SSH into device on port T2"
	echo "  rpi-power-hat ssh B1 ls  # SSH into device on port B1 and run 'ls' command"
}

# Read configuration value
read_config() {
	local section="$1"
	local key="$2"
	
	awk -F= -v section="[$section]" -v key="$key" '
		$0 == section { in_section = 1; next }
		/^\[/ && in_section { in_section = 0 }
		in_section && $1 == key { print $2; exit }
	' "$CONFIG_FILE"
}


# Main function
main() {
	local port="$1"

	shift
	local remote_cmd=( "$@" )
	
	if [[ -z "$port" || "$port" = "-h" || "$port" = "--help" || "$port" = "-help" ]]; then
		if [[ -z "$port" ]]; then
			echo "Error: Port is required" >&2
		fi
		print_usage
		exit 0
	fi
	
	if ! validate_port "$port"; then
		echo "Error: Invalid port '$port'. Valid ports are: $(list_ports)" >&2
		exit 1
	fi
	
	if [[ ! -f "$CONFIG_FILE" ]]; then
		echo "Error: Config file '$CONFIG_FILE' not found" >&2
		exit 1
	fi
	
	# Read SSH configuration (keys and IdentityFile are configured via ~/.ssh includes)
	local ssh_host
	ssh_host="$(read_config "$port" "ssh_host")"
	local ssh_user
	ssh_user="$(read_config "$port" "username")"
	
	# Fall back to DEFAULT section if not found
	[[ -z "$ssh_host" ]] && ssh_host="$(read_config "DEFAULT" "ssh_host")"
	[[ -z "$ssh_user" ]] && ssh_user="$(read_config "DEFAULT" "username")"
	
	if [[ -z "$ssh_host" || -z "$ssh_user" ]]; then
		echo "Error: Missing SSH configuration for port $port" >&2
		echo "Required: ssh_host and username in ports.conf (DEFAULT or $port section)" >&2
		exit 1
	fi
	
	echo "Connecting to $ssh_user@$ssh_host (port $port)..."
	
	# Connect via SSH
	ssh \
		-o StrictHostKeyChecking=no \
		-o UserKnownHostsFile=/dev/null \
		-o LogLevel=ERROR \
		"$ssh_user"@"$ssh_host" "${remote_cmd[@]}"
}

main "$@"