#!/usr/bin/env bash
#
# setup-shared-projects.sh
#
# Prepare the shared Claude Code projects/ tree used by claude-failover
# to preserve session resume across account swaps.
#
# Creates /home/ubuntu/.claude-projects-shared (if missing), then rewires
# each account's ~/.claude/projects to point at it. Existing per-account
# transcripts are merged into the shared tree (rsync -a, no overwrite of
# newer files).
#
# Usage:
#   scripts/setup-shared-projects.sh [--shared DIR] [--dry-run] \
#       account_home_1 account_home_2 [account_home_N...]
#
# Example:
#   scripts/setup-shared-projects.sh \
#       /home/ubuntu/.claude-compte1 \
#       /home/ubuntu/.claude-compte2
#
# Safe to rerun: it never deletes account-private files (credentials,
# statsig cache, settings). It only touches the `projects/` subdir.

set -euo pipefail

SHARED="/home/ubuntu/.claude-projects-shared"
DRY_RUN=0
ACCOUNTS=()

while [[ $# -gt 0 ]]; do
    case "$1" in
        --shared)
            SHARED="$2"
            shift 2
            ;;
        --dry-run)
            DRY_RUN=1
            shift
            ;;
        -h|--help)
            sed -n '2,22p' "$0"
            exit 0
            ;;
        *)
            ACCOUNTS+=("$1")
            shift
            ;;
    esac
done

if [[ ${#ACCOUNTS[@]} -lt 1 ]]; then
    echo "error: at least one account home must be provided" >&2
    exit 2
fi

run() {
    if [[ $DRY_RUN -eq 1 ]]; then
        echo "DRY: $*"
    else
        echo "+ $*"
        "$@"
    fi
}

run mkdir -p "$SHARED"

for home in "${ACCOUNTS[@]}"; do
    if [[ ! -d "$home" ]]; then
        echo "warn: account home not found: $home (skipping)" >&2
        continue
    fi
    proj="$home/.claude/projects"
    run mkdir -p "$home/.claude"

    if [[ -L "$proj" ]]; then
        current="$(readlink "$proj")"
        if [[ "$current" == "$SHARED" ]]; then
            echo "ok: $proj already -> $SHARED"
            continue
        fi
        echo "replacing symlink $proj ($current -> $SHARED)"
        run rm "$proj"
    elif [[ -d "$proj" ]]; then
        echo "merging $proj -> $SHARED"
        run rsync -a --ignore-existing "$proj/" "$SHARED/"
        run rm -rf "$proj"
    fi

    run ln -s "$SHARED" "$proj"
done

echo "done. shared projects tree: $SHARED"
