#!/bin/bash

# SCP files to 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 "SCP file transfer tool for rpi-power-hat devices"
	echo "Usage: rpi-power-hat scp <port> <local_path>:<remote_path>"
	echo
	echo "Available ports: B1, B2, T1, T2"
	echo
	echo "Examples:"
	echo "  rpi-power-hat scp B1 ./file.deb:/tmp/file.deb   # Copy file to device on port B1"
	echo "  rpi-power-hat scp T2 ./image.img:/home/pi/img    # Copy file to device on port T2"
}

# 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 filespec="$1"

	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

	if [[ -z "$filespec" || "$filespec" != *:* ]]; then
		echo "Error: File spec must be in the format local_path:remote_path" >&2
		print_usage
		exit 1
	fi

	local local_path="${filespec%%:*}"
	local remote_path="${filespec#*:}"

	# 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 "Copying $local_path to $ssh_user@$ssh_host:$remote_path (port $port)..." >&2

	# Copy via SCP
	scp \
		-o StrictHostKeyChecking=no \
		-o UserKnownHostsFile=/dev/null \
		-o LogLevel=ERROR \
		"$local_path" "$ssh_user"@"$ssh_host":"$remote_path"
}

main "$@"
