#!/bin/bash
#
# Copyright (c) 2026 Keith Maton G6NHU
# https://qso365.co.uk
#
# Permission is granted to use, copy, modify and distribute this script,
# provided that this notice is retained.
# You may not misrepresent the original authorship of this work.
#

set -e

BASE_URL="https://raw.githubusercontent.com/openhamclock/hamclock/refs/heads/main/debian"
DEST="/usr/local/bin"
FILES=("csi" "fix-hosts" "hcdc" "ohb" "what")

# Must be run as root
if [ "$EUID" -ne 0 ]; then
    echo "Please run with sudo."
    exit 1
fi

echo "Installing tools to $DEST..."

# Check destination exists
if [ ! -d "$DEST" ]; then
    echo "Error: $DEST does not exist."
    exit 1
fi

# Prefer curl, fall back to wget
download() {
    url="$1"
    out="$2"

    if command -v curl >/dev/null 2>&1; then
        curl -fsSL "$url" -o "$out"
    elif command -v wget >/dev/null 2>&1; then
        wget -qO "$out" "$url"
    else
        echo "Error: neither curl nor wget is available."
        exit 1
    fi
}

for f in "${FILES[@]}"; do
    echo "Installing $f..."
    download "$BASE_URL/$f" "$DEST/$f"
    chmod 755 "$DEST/$f"
done

echo
echo "Installation complete."
echo "You can now run: csi, fix-hosts, hcdc, ohb, what"