#!/usr/bin/env bash
#
# Safe installation script for claude-code-status-line
# This script safely replaces the binary to avoid file locking issues
#

set -e  # Exit on error

# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Determine platform
case "$(uname -s)" in
    Darwin|Linux)
        INSTALL_DIR="$HOME/.claude/statusline"
        ;;
    MINGW*|MSYS*|CYGWIN*)
        INSTALL_DIR="$USERPROFILE/.claude/statusline"
        ;;
    *)
        echo -e "${RED}Unsupported platform: $(uname -s)${NC}"
        exit 1
        ;;
esac

BINARY_NAME="claude-code-status-line"
BUILD_MODE="${1:-release}"  # Default to release, can pass "debug" as arg

# Validate build mode
if [[ "$BUILD_MODE" != "release" && "$BUILD_MODE" != "debug" ]]; then
    echo -e "${RED}Error: Build mode must be 'release' or 'debug'${NC}"
    echo "Usage: $0 [release|debug]"
    exit 1
fi

echo -e "${BLUE}Building $BUILD_MODE binary...${NC}"
if [[ "$BUILD_MODE" == "release" ]]; then
    cargo build --release
    SOURCE_BINARY="target/release/$BINARY_NAME"
else
    cargo build
    SOURCE_BINARY="target/debug/$BINARY_NAME"
fi

# Check if binary was built successfully
if [[ ! -f "$SOURCE_BINARY" ]]; then
    echo -e "${RED}Error: Binary not found at $SOURCE_BINARY${NC}"
    exit 1
fi

echo -e "${BLUE}Installing to $INSTALL_DIR...${NC}"

# Create directory if it doesn't exist
mkdir -p "$INSTALL_DIR"

# Atomic installation to avoid file locking issues:
# 1. Copy to temporary file
# 2. Set executable permissions
# 3. Atomically move (replace) the old binary
TEMP_BINARY="$INSTALL_DIR/${BINARY_NAME}.new"
TARGET_BINARY="$INSTALL_DIR/$BINARY_NAME"

cp "$SOURCE_BINARY" "$TEMP_BINARY"
chmod +x "$TEMP_BINARY"
mv -f "$TEMP_BINARY" "$TARGET_BINARY"

echo -e "${GREEN}✓ Successfully installed $BUILD_MODE build to:${NC}"
echo -e "${GREEN}  $TARGET_BINARY${NC}"
echo ""
echo "You may need to restart Claude Code to see changes."
