#!/bin/bash
#
# cmdr - Open directories in Commander.app
#
# Usage:
#   cmdr [path]      Open path (or current directory) in Commander
#   cmdr --help      Show this help message
#   cmdr --version   Show version information
#

set -euo pipefail

APP_BUNDLE_ID="com.krzyzanowskim.Commander"
APP_DEBUG_BUNDLE_ID="com.krzyzanowskim.Commander.debug"

version() {
    echo "cmdr - CLI for Commander.app"
}

usage() {
    cat <<EOF
Usage: cmdr [options] [path ...]

Open directories in Commander.app

Arguments:
  path          Directory to open (defaults to current directory)
                Multiple paths can be specified.

Options:
  -h, --help    Show this help message
  -v, --version Show version information

Examples:
  cmdr                 Open current directory
  cmdr ~/projects/app  Open specific directory
  cmdr . ../other      Open multiple directories
EOF
}

# Find the Commander app bundle ID to use (prefer release, fall back to debug)
find_bundle_id() {
    if mdfind "kMDItemCFBundleIdentifier == '$APP_BUNDLE_ID'" 2>/dev/null | head -1 | grep -q .; then
        echo "$APP_BUNDLE_ID"
    elif mdfind "kMDItemCFBundleIdentifier == '$APP_DEBUG_BUNDLE_ID'" 2>/dev/null | head -1 | grep -q .; then
        echo "$APP_DEBUG_BUNDLE_ID"
    else
        echo "$APP_BUNDLE_ID"
    fi
}

open_path() {
    local target="$1"
    local bundle_id="$2"

    # Resolve to absolute path without resolving symlinks
    if [[ "$target" != /* ]]; then
        target="$PWD/$target"
    fi

    if [[ ! -e "$target" ]]; then
        echo "cmdr: cannot access '$1': No such file or directory" >&2
        return 1
    fi

    if [[ ! -d "$target" ]]; then
        echo "cmdr: '$1' is not a directory" >&2
        return 1
    fi

    open -b "$bundle_id" "$target"
}

main() {
    local paths=()

    while [[ $# -gt 0 ]]; do
        case "$1" in
            -h|--help)
                usage
                exit 0
                ;;
            -v|--version)
                version
                exit 0
                ;;
            --)
                shift
                paths+=("$@")
                break
                ;;
            -*)
                echo "cmdr: unknown option '$1'" >&2
                echo "Try 'cmdr --help' for more information." >&2
                exit 1
                ;;
            *)
                paths+=("$1")
                ;;
        esac
        shift
    done

    # Default to current directory
    if [[ ${#paths[@]} -eq 0 ]]; then
        paths=(".")
    fi

    local bundle_id
    bundle_id="$(find_bundle_id)"

    local exit_code=0
    for path in "${paths[@]}"; do
        open_path "$path" "$bundle_id" || exit_code=1
    done

    exit "$exit_code"
}

main "$@"
