#!/bin/bash
# Install corporate memory rule files to user's home directory.
# Called by webapp (www-data) via sudo after a user votes.
#
# Usage: sudo install-user-rules USERNAME SOURCE_DIR
#   USERNAME   - Linux username whose home dir will receive the rules
#   SOURCE_DIR - Temporary directory containing .md rule files to install
#
# The script:
# 1. Creates /home/{user}/.claude_rules/ if needed
# 2. Removes old km_*.md files
# 3. Copies new .md files from SOURCE_DIR with proper ownership
# 4. Cleans up - caller is responsible for removing SOURCE_DIR

set -euo pipefail

if [[ $EUID -ne 0 ]]; then
    echo "Must be run as root (via sudo)" >&2
    exit 1
fi

if [[ $# -lt 2 ]]; then
    echo "Usage: sudo install-user-rules USERNAME SOURCE_DIR" >&2
    exit 1
fi

USERNAME="$1"
SOURCE_DIR="$2"

# Validate username exists on the system
if ! id "$USERNAME" &>/dev/null; then
    echo "User '$USERNAME' does not exist" >&2
    exit 1
fi

# Validate source directory
if [[ ! -d "$SOURCE_DIR" ]]; then
    echo "Source directory '$SOURCE_DIR' does not exist" >&2
    exit 1
fi

USER_HOME=$(eval echo "~${USERNAME}")
RULES_DIR="${USER_HOME}/.claude_rules"

# Create rules directory with user ownership (700 = owner only)
mkdir -p "$RULES_DIR"
chown "${USERNAME}:${USERNAME}" "$RULES_DIR"
chmod 700 "$RULES_DIR"

# Remove old rule files (km_*.md pattern only, preserve anything else)
rm -f "${RULES_DIR}"/km_*.md

# Install new rule files from source directory
COUNT=0
for src_file in "${SOURCE_DIR}"/*.md; do
    if [[ -f "$src_file" ]]; then
        /usr/bin/install -o "$USERNAME" -g "$USERNAME" -m 600 "$src_file" "$RULES_DIR/"
        COUNT=$((COUNT + 1))
    fi
done

echo "Installed ${COUNT} rules for ${USERNAME} in ${RULES_DIR}"
