#!/bin/sh
# crc — "claude remote", in a fresh iTerm window.
#
# Thin launcher over `rclaude`: opens a NEW iTerm2 window and starts a durable
# remote Claude Code session in a target directory on a target host. Unlike the
# `cc` alias (which takes over the current tab), this spawns its own window so
# the current shell is left alone.
#
# Usage:
#   crc                      # apricot.lan, mirror of $PWD
#   crc <host>               # <host>, mirror of $PWD
#   crc <host> <dir>         # <host>, explicit dir
#   crc -h | --help
#
# Env:
#   CRC_HOST   default host when none given (default: apricot.lan)
#
# Everything host/dir/mirror/tmux-related is delegated to `rclaude`; this script
# only owns the "new iTerm window" part.

set -eu

host=${CRC_HOST:-apricot.lan}
dir=$PWD

case "${1:-}" in
    -h|--help)
        sed -n '2,18p' "$0" | sed 's/^# \{0,1\}//'
        exit 0
        ;;
esac

[ $# -ge 1 ] && host=$1
[ $# -ge 2 ] && dir=$2

command -v rclaude >/dev/null 2>&1 || {
    echo "crc: rclaude not found on PATH" >&2
    exit 127
}

# Build the command the new window will run. rclaude resolves the local->remote
# mirror itself, so we just hand it host + dir verbatim.
inner="rclaude $(printf %q "$host") $(printf %q "$dir")"

# Escape for embedding inside an AppleScript double-quoted string.
escaped=$(printf %s "$inner" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g')

osascript <<OSA
tell application "iTerm"
    activate
    create window with default profile
    tell current session of current window
        write text "${escaped}"
    end tell
end tell
OSA
