#!/bin/bash

# ---------------------------------------------------------------------------------
# Kanata install recipe
# Downloads the latest Linux binary from GitHub, installs to ~/.local/bin,
# and sets up a systemd user service.
# ---------------------------------------------------------------------------------

set -e

INSTALL_DIR="$HOME/.local/bin"
CONFIG_DIR="$HOME/.config/kanata"
SERVICE_PATH="/lib/systemd/system/kanata.service"
BINARY_NAME="kanata"

# ---------------------------------------------------------------------------------
# Fetch latest release version from GitHub API
# ---------------------------------------------------------------------------------
echo "🔍 Fetching latest Kanata release..."
LATEST_VERSION=$(curl -fsSL "https://api.github.com/repos/jtroo/kanata/releases/latest" | grep '"tag_name"' | head -1 | grep -o 'v[0-9.]*')

if [ -z "$LATEST_VERSION" ]; then
    echo "❌ Failed to fetch latest Kanata version."
    exit 1
fi

echo "✅ Latest Kanata version: $LATEST_VERSION"

# ---------------------------------------------------------------------------------
# Download binary
# ---------------------------------------------------------------------------------
DOWNLOAD_URL="https://github.com/jtroo/kanata/releases/download/${LATEST_VERSION}/kanata_linux_x64"

echo "📦 Downloading kanata_linux_x64..."
mkdir -p "$INSTALL_DIR"
curl -fsSL "$DOWNLOAD_URL" -o "$INSTALL_DIR/$BINARY_NAME"
chmod +x "$INSTALL_DIR/$BINARY_NAME"

echo "✅ Installed: $INSTALL_DIR/$BINARY_NAME"

# ---------------------------------------------------------------------------------
# Verify a config file exists
# ---------------------------------------------------------------------------------
if [ ! -f "$CONFIG_DIR/kanata.kbd" ]; then
    echo "⚠️  No config found at $CONFIG_DIR/kanata.kbd"
    echo "   Make sure your dotfiles are synced before enabling the service."
fi

# ---------------------------------------------------------------------------------
# Write systemd service file
# ---------------------------------------------------------------------------------
echo "⚙️  Writing systemd service to $SERVICE_PATH..."

sudo tee "$SERVICE_PATH" > /dev/null <<EOF
[Unit]
Description=Kanata keyboard remapper
Documentation=https://github.com/jtroo/kanata

[Service]
Type=simple
ExecStart=$INSTALL_DIR/$BINARY_NAME --cfg $CONFIG_DIR/kanata.kbd
Restart=never

[Install]
WantedBy=default.target
EOF

echo "✅ Service file written."

# ---------------------------------------------------------------------------------
# Enable and start the service
# ---------------------------------------------------------------------------------
echo "🚀 Enabling and starting kanata service..."
sudo systemctl daemon-reload
sudo systemctl enable kanata.service
sudo systemctl start kanata.service

echo ""
echo "✅ Kanata setup complete."
echo "   Binary : $INSTALL_DIR/$BINARY_NAME"
echo "   Config : $CONFIG_DIR/kanata.kbd"
echo "   Service: systemctl status kanata"

