#\!/usr/bin/env bash
# AiSrt installer for Linux/macOS

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
INSTALL_BIN="/usr/local/bin"
CONFIG_DIR="$HOME/.config/aisrt"

echo ""
echo "Installing AiSrt..."
echo ""

# Check root/sudo
if [ "$(id -u)" -ne 0 ]; then
    echo "Error: This script must be run with sudo." >&2
    echo "Usage: sudo ./install.sh" >&2
    exit 1
fi

# Resolve actual user home when running under sudo
ACTUAL_USER="${SUDO_USER:-$USER}"
ACTUAL_HOME=$(eval echo "~$ACTUAL_USER")
CONFIG_DIR="$ACTUAL_HOME/.config/aisrt"

# Copy executable
if [ \! -f "$SCRIPT_DIR/aisrt" ]; then
    echo "Error: aisrt not found in $SCRIPT_DIR" >&2
    exit 1
fi

cp "$SCRIPT_DIR/aisrt" "$INSTALL_BIN/aisrt"
chmod +x "$INSTALL_BIN/aisrt"
echo "  Copied aisrt to $INSTALL_BIN/"

# Copy config
if [ -f "$SCRIPT_DIR/appsettings.json" ]; then
    mkdir -p "$CONFIG_DIR"
    if [ \! -f "$CONFIG_DIR/appsettings.json" ]; then
        cp "$SCRIPT_DIR/appsettings.json" "$CONFIG_DIR/appsettings.json"
        chown "$ACTUAL_USER" "$CONFIG_DIR/appsettings.json"
        echo "  Copied appsettings.json to $CONFIG_DIR/"
    else
        echo "  appsettings.json already exists in $CONFIG_DIR/, skipping"
    fi
    chown "$ACTUAL_USER" "$CONFIG_DIR"
fi

echo ""
echo "AiSrt installed successfully\!"
echo "Run 'aisrt --help' to get started."
echo ""
