#!/bin/bash
set -euo pipefail

# Claude Code CLI - Setup User Script
# Creates the claude-code user and copies credentials from root

USER_NAME="claude-code"
SOURCE_DIR="/root/.claude"
TARGET_DIR="/home/$USER_NAME/.claude"

echo "Setting up Claude Code user..."

# Check if user already exists
if id "$USER_NAME" &>/dev/null; then
    echo "User '$USER_NAME' already exists (UID: $(id -u $USER_NAME))"
else
    # Create the user
    useradd -m -s /bin/bash "$USER_NAME"
    echo "Created user '$USER_NAME' (UID: $(id -u $USER_NAME))"
fi

# Check if root credentials exist
if [ ! -f "$SOURCE_DIR/.credentials.json" ]; then
    echo "ERROR: No credentials found at $SOURCE_DIR/.credentials.json"
    echo "Please run the OAuth authentication flow first (see SKILL.md Step 1)"
    exit 1
fi

# Create target .claude directory
mkdir -p "$TARGET_DIR"

# Copy credentials
cp "$SOURCE_DIR/.credentials.json" "$TARGET_DIR/"
echo "Copied credentials from $SOURCE_DIR/.credentials.json"

# Copy settings if it exists (optional but helpful)
if [ -f "$SOURCE_DIR/settings.json" ]; then
    cp "$SOURCE_DIR/settings.json" "$TARGET_DIR/"
    echo "Copied settings from $SOURCE_DIR/settings.json"
fi

# Set correct ownership
chown -R "$USER_NAME:$USER_NAME" "$TARGET_DIR"
echo "Set ownership to $USER_NAME:$USER_NAME"

# Verify
echo ""
echo "Setup complete! Verify with:"
echo "  ls -la $TARGET_DIR/.credentials.json"
echo ""
echo "Run Claude CLI as the new user:"
echo "  sudo -u $USER_NAME claude --dangerously-skip-permissions -p \"hello\""