#!/bin/bash

# Print current hostname or show hostname history for a port

# Source hardware configuration reader (dev or installed)
source "/usr/share/rpi-power-hat/scripts/hardware-reader.sh"

# Determine config and history paths, skip if not found
if [ -f "/etc/rpi-power-hat/ports.conf" ]; then
    CONFIG_FILE="/etc/rpi-power-hat/ports.conf"
else
    CONFIG_FILE=""
fi

HISTORY_DIR="/var/lib/rpi-power-hat/history"

print_usage() {
	echo "Get hostname for a port, or show hostname history"
	echo "Usage: rpi-power-hat get-hostname <port> [-h|--history]"
	echo
	echo "Examples:"
	echo "  rpi-power-hat get-hostname B1"
	echo "  rpi-power-hat get-hostname B2 -h"
}

# Map model strings to a human-friendly device name
friendly_model_name() {
	local m="$1"
	[ -n "$m" ] || { echo "-"; return 0; }
	case "$m" in
		5)
			echo "Pi 5" ;;
		4)
			echo "Pi 4" ;;
		0)
			echo "Pi Zero 2 W" ;;
		*)
			echo "$m" ;;
	esac
}

# Read configuration value (simple INI parser for key within [SECTION])
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 { sub(/^\s+/, "", $2); print $2; exit }
	' "$CONFIG_FILE"
}

print_current_hostname() {
	local port="$1"
	if [ -z "$CONFIG_FILE" ] || [ ! -f "$CONFIG_FILE" ]; then
		echo "Error: ports.conf not found" >&2
		return 1
	fi

	local host
	host="$(read_config "$port" "hostname")"
	if [ -z "$host" ]; then
		host="$(read_config "$port" "ssh_host")"
	fi
	if [ -z "$host" ]; then
		host="$(read_config "DEFAULT" "hostname")"
	fi
	if [ -z "$host" ]; then
		host="$(read_config "DEFAULT" "ssh_host")"
	fi

	if [ -z "$host" ]; then
		echo "Error: hostname not set for port $port" >&2
		return 1
	fi

	echo "$host"
}

print_history() {
    local port="$1"

    # Collect matching history files
    shopt -s nullglob
    local files=("$HISTORY_DIR"/*_"$port"_*.log)
    shopt -u nullglob

    if [ ${#files[@]} -eq 0 ]; then
        # No history; print nothing (or notify on stderr)
        echo "No history entries found for port $port" >&2
        return 0
    fi

    # Sort newest first based on filename (timestamp prefix)
    local IFS=$'\n'
    local sorted=($(printf "%s\n" "${files[@]}" | sort -r))
    unset IFS

    for file in "${sorted[@]}"; do
        # Prefer values from file content
        local ts="$(grep -m1 '^timestamp=' "$file" | cut -d= -f2)"
        local model_raw="$(grep -m1 '^model=' "$file" | cut -d= -f2)"
        local host="$(grep -m1 '^hostname=' "$file" | cut -d= -f2)"

        # Fallbacks from filename if needed
        if [ -z "$ts" ]; then
            local base
            base="$(basename "$file")"  # e.g. 2025-08-21_12-30-00_B1_rpi-B1-xxxx.log
            ts="${base%%_*}"
        fi

        if [ -z "$host" ]; then
            local base
            base="$(basename "$file")"
            host="${base%.log}"
            host="${host#*_${port}_}"
        fi

        # If model not present in history (older files), try ports.conf
        if [ -z "$model_raw" ] && [ -n "$CONFIG_FILE" ] && [ -f "$CONFIG_FILE" ]; then
            model_raw="$(read_config "$port" "model")"
        fi

        local dev_label
        dev_label="$(friendly_model_name "$model_raw")"

        echo "$ts | $dev_label | $host"
    done
}

main() {
	local port=""
	local show_history=false

	# Help
	if [ "$1" = "--help" ] || [ "$1" = "help" ]; then
		print_usage
		exit 0
	fi

	# Parse args: support either order for -h/--history and port
	for arg in "$@"; do
		case "$arg" in
			-h|--history)
				show_history=true
				;;
			*)
				if [ -z "$port" ]; then
					port="$arg"
				else
					echo "Error: unexpected argument '$arg'" >&2
					print_usage
					exit 1
				fi
				;;
		esac
	done

	if [ -z "$port" ]; then
		echo "Error: port is required" >&2
		print_usage
		exit 1
	fi

	if ! validate_port "$port"; then
		echo "Error: Invalid port '$port'. Valid ports are: $(list_ports)" >&2
		exit 1
	fi

	if [ "$show_history" = true ]; then
		print_history "$port"
	else
		print_current_hostname "$port"
	fi
}

main "$@"


