#!/bin/bash
#version=1.2.1

# update - safely update a script from ~/bin/claude/[scriptname]/ to ~/bin/
#
# This script automates the process of updating scripts from their development
# directory to the production bin directory. It automatically uses vc (version
# control) to save earlier versions before overwriting, ensuring you can always
# rollback to a previous version if needed.
#
# Usage: update scriptname
#        (or just 'update' from within ~/bin/claude/scriptname/ directory)
#
# The script will:
#   1. Check if a vc backup exists for the current version (see vc script)
#   2. If not, automatically run 'vc scriptname' to create a backup
#   3. Copy the new version from ~/bin/claude/scriptname/ to ~/bin/
#   4. Set executable permissions

SCRIPT_NAME="${1}"
BIN_DIR="$HOME/bin"
DEV_DIR="$HOME/bin/claude"
VC_DIR="$HOME/bin/vc_version_check"

# If no argument provided, try to infer from current directory
if [[ -z "$SCRIPT_NAME" ]]; then
    CURRENT_DIR=$(basename "$(pwd)")
    PARENT_DIR=$(basename "$(dirname "$(pwd)")")

    if [[ "$PARENT_DIR" == "claude" ]]; then
        SCRIPT_NAME="$CURRENT_DIR"
        echo "Inferring script name from directory: $SCRIPT_NAME"
    else
        echo "Error: Please provide script name or run from within ~/bin/claude/[scriptname]/"
        echo "Usage: update scriptname"
        exit 1
    fi
fi

SOURCE_FILE="$DEV_DIR/$SCRIPT_NAME/$SCRIPT_NAME"
TARGET_FILE="$BIN_DIR/$SCRIPT_NAME"
VC_BACKUP_DIR="$VC_DIR/$SCRIPT_NAME"

# Check if source file exists
if [[ ! -f "$SOURCE_FILE" ]]; then
    echo "Error: Source file not found: $SOURCE_FILE"
    exit 1
fi

# Check if target file exists
if [[ ! -f "$TARGET_FILE" ]]; then
    echo "Warning: Target file does not exist: $TARGET_FILE"
    echo "This appears to be a new script. Copying without version control..."
    cp "$SOURCE_FILE" "$TARGET_FILE"
    chmod +x "$TARGET_FILE"
    echo "Copied $SOURCE_FILE to $TARGET_FILE"
    exit 0
fi

# Function to extract version from a script
extract_version() {
    local file="$1"
    # Search first 10 lines for version pattern (case insensitive)
    local version=$(head -n 10 "$file" 2>/dev/null | grep -iE "^#\s*version" | head -n 1 | sed -E 's/^#\s*version\s*=?\s*([0-9]+\.[0-9]+(\.[0-9]+)?).*/\1/')

    if [[ -z "$version" ]]; then
        echo "0.0.0"
    else
        echo "$version"
    fi
}

# Compare source and target versions
SOURCE_VERSION=$(extract_version "$SOURCE_FILE")
SOURCE_SIZE=$(stat -c%s "$SOURCE_FILE" 2>/dev/null || stat -f%z "$SOURCE_FILE" 2>/dev/null)
TARGET_VERSION=$(extract_version "$TARGET_FILE")
TARGET_SIZE=$(stat -c%s "$TARGET_FILE" 2>/dev/null || stat -f%z "$TARGET_FILE" 2>/dev/null)

echo "Target: v$TARGET_VERSION (${TARGET_SIZE} bytes) | Source: v$SOURCE_VERSION (${SOURCE_SIZE} bytes)"

# Check if source and target are identical
if [[ "$SOURCE_VERSION" == "$TARGET_VERSION" && "$SOURCE_SIZE" == "$TARGET_SIZE" ]]; then
    echo "✓ No update needed - source and target are identical"
    exit 0
fi

# Check if we need to backup the current version before overwriting
NEED_BACKUP=true

if [[ -d "$VC_BACKUP_DIR" && -n "$(ls -A "$VC_BACKUP_DIR" 2>/dev/null)" ]]; then
    # Look for existing backups of the target version
    for backup in "$VC_BACKUP_DIR"/*; do
        if [[ -f "$backup" ]]; then
            # Check if backup filename contains this version
            if [[ "$backup" =~ \[v${TARGET_VERSION}\] ]]; then
                BACKUP_SIZE=$(stat -c%s "$backup" 2>/dev/null || stat -f%z "$backup" 2>/dev/null)
                if [[ "$BACKUP_SIZE" == "$TARGET_SIZE" ]]; then
                    echo "✓ Current version already backed up"
                    NEED_BACKUP=false
                    break
                else
                    echo "Note: Found backup for v$TARGET_VERSION but size differs (${BACKUP_SIZE} vs ${TARGET_SIZE} bytes)"
                fi
            fi
        fi
    done
fi

if [[ "$NEED_BACKUP" == "true" ]]; then
    echo "Creating backup of v$TARGET_VERSION before overwriting..."
    vc "$SCRIPT_NAME"
    if [[ $? -ne 0 ]]; then
        echo "Error: Failed to create vc backup"
        exit 1
    fi
fi

# Copy the new version
echo "Updating $SCRIPT_NAME..."
cp "$SOURCE_FILE" "$TARGET_FILE"
chmod +x "$TARGET_FILE"

# Backup the newly installed version
echo "Creating backup of new v$SOURCE_VERSION..."
vc "$SCRIPT_NAME"
if [[ $? -ne 0 ]]; then
    echo "Warning: Failed to create vc backup of new version (but update succeeded)"
fi

echo "✓ Successfully updated to v$SOURCE_VERSION"
