#!/usr/bin/env bash
# ssr — System Sync & Restore CLI dispatcher.
# Resolves the repository root, sources libs, and forwards to a subcommand.

set -euo pipefail

# Resolve script directory even when invoked via a symlink (e.g. /usr/local/bin/ssr).
SOURCE="${BASH_SOURCE[0]}"
while [[ -L "$SOURCE" ]]; do
    DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
    SOURCE="$(readlink "$SOURCE")"
    [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE"
done
SSR_BIN_DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
SSR_ROOT="$(cd "$SSR_BIN_DIR/.." && pwd)"
export SSR_ROOT SSR_BIN_DIR

# shellcheck source=../lib/common.sh
source "$SSR_ROOT/lib/common.sh"

usage() {
    cat <<EOF
ssr — System Sync & Restore for macOS

Usage:
  ssr <command> [options]

Commands:
  install              First-time install: links binary, seeds config, schedules sync.
  sync                 Run a backup: brew bundle dump + mackup backup → cloud.
  restore [Brewfile]   Restore a machine: brew bundle + mackup restore + macOS defaults.
  update [--dry-run]   Pull latest ssr code, refresh launchd if needed.
  schedule on|off      Enable/disable the scheduled launchd sync job.
  config show|edit     Print or edit the active config file.
  status               Show last sync time, cloud target, and scheduled state.
  version              Print version.

Options:
  -c, --config PATH    Use a specific config file (default: ~/.config/ssr/ssr.conf).
  -h, --help           Show this help.

Environment:
  SSR_CONFIG           Same as --config.

Docs: see README.md in the repository root.
EOF
}

# Parse global flags.
while [[ $# -gt 0 ]]; do
    case "$1" in
        -c|--config) export SSR_CONFIG="$2"; shift 2 ;;
        -h|--help)   usage; exit 0 ;;
        --) shift; break ;;
        -*) ssr::die "Unknown global flag: $1 (use -h for help)" ;;
        *)  break ;;
    esac
done

[[ $# -gt 0 ]] || { usage; exit 1; }

cmd="$1"; shift
case "$cmd" in
    install|sync|restore|update|schedule|config|status)
        target="$SSR_BIN_DIR/ssr-$cmd"
        [[ -x "$target" ]] || ssr::die "Subcommand not executable: $target"
        exec "$target" "$@"
        ;;
    version|-v|--version)
        cat "$SSR_ROOT/VERSION" 2>/dev/null || echo "dev"
        ;;
    help|-h|--help) usage ;;
    *) ssr::err "Unknown command: $cmd"; usage; exit 1 ;;
esac
