#!/usr/bin/env bash
# brt — Brew Remote Tools: a Swiss-army CLI for networking, editing, and remote access.
set -euo pipefail

_brt_resolve_install_dir() {
  local script="$1" dir target
  dir=$(cd "$(dirname "$script")" && pwd)
  if [[ -L "$script" ]]; then
    target=$(readlink "$script")
    [[ "$target" != /* ]] && target="${dir}/${target}"
    dir=$(cd "$(dirname "$target")" && pwd)
  fi
  echo "$dir"
}

BRT_DIR="${BRT_DIR:-$(_brt_resolve_install_dir "${BASH_SOURCE[0]}")}"
BRT_LIB="${BRT_DIR}/lib"

source "${BRT_LIB}/common.sh"
brt_load_config

# Version file is the source of truth (updated by install/update)
_BRT_EMBEDDED_VERSION="1.5.39"
BRT_VERSION="$(brt_read_version "$BRT_DIR")"
BRT_VERSION="${BRT_VERSION:-${_BRT_EMBEDDED_VERSION}}"

usage() {
  cat <<EOF
brt — Brew Remote Tools v${BRT_VERSION}

Usage: brt -<command> [args...]

Networking
  -ip [check|local|public|interfaces]     Show IP information
  -dns <host> [type]                       DNS lookup (A, AAAA, MX, TXT, NS, CNAME)
  -reverse <ip>                            Reverse DNS lookup
  -portscan <host> [ports|start-end]       Scan ports (default: common ports)
  -ping <host> [-c count]                  Ping host
  -whois <domain|ip>                       WHOIS lookup
  -traceroute <host>                       Trace route to host
  -headers <url>                           Fetch HTTP response headers
  -ssl <host> [port]                       Check SSL certificate and expiry
  -curl <url> [curl flags...]              Enhanced curl with timing info
  -post <url> [curl flags...]              Send HTTP POST request

Text & Data
  -edit <file>                             Nano-style terminal text editor
  -json [file|-]                           Pretty-print JSON
  -encode <string|file>                    Base64 encode
  -decode <string|file>                    Base64 decode
  -hash <algo> <input>                     Hash (md5, sha1, sha256, sha512)
  -urlencode <string>                      URL-encode a string
  -urldecode <string>                      URL-decode a string
  -uuid                                    Generate a random UUID
  -pass [length]                           Generate a secure password
  -grep <pattern> [path...]                Search files with line numbers

  Media
  -image <file> [-x cols] [-y rows]           Render an image in the terminal
  -video <file|url> [--no-audio]              Play video in terminal via mpv (file, URL, YouTube)
  -doom [--wad file] [--scaling N]           Play Doom in the terminal (WASD + arrows)
  -browse "query"                            Google search in the terminal (top 25 results)

  System
  -run <cmd;wait N;cmd...>                 Run chained commands (wait in seconds)
                                              brt -run 'echo hi;wait 2;echo bye'
                                              brt -run echo hi wait 2 echo bye
  -serve <port> [directory]                Start a static file server
  -watch <cmd>                             Re-run command every 2 seconds
  -listen [port]                            Show listening ports or check one port
  -killport <port>                         Kill process using a port
  -env [pattern]                           Show environment variables
  -which-all <cmd>                         Find all instances of a command
  -du [path] [depth]                       Disk usage summary
  -extract <archive> [dest]                Extract zip/tar/tar.gz archives
  -sysinfo                                 Show system information
  -publickey [key.pub]                     Show (and copy) SSH public key
  -timestamp [now|unix|date]               Convert or show timestamps
  -timer <seconds> [message]               Countdown timer with alert
  -calc <expression>                       Calculator (uses bc)

Remote Access
  -access serve [-p port]                  Start relay + live console (stop/disconnect at prompt)
  -access connect <host:port> <token>      Connect to a remote brt terminal relay
  -access leave                           Disconnect your own client session
  -access clients                         List connected sessions (6-char ids)
  -access disconnect [<id>]               Disconnect yourself, or a session by id
  -access logs                            Live audit console (stop · disconnect · clear · quit)
  -access clear-logs                      Clear serve audit and process logs
  -access status                           Show running access server info
  -access stop [-f]                        Stop the access server
  -access force-stop [-p port]              Kill all access servers + free the port

Other
  -config [edit|show|path]                  Edit ~/.brt/.env (API keys, preferences)
  -speed                                   Quick download speed test
  -weather [location]                      Current weather (via wttr.in)
  -qr <text>                               Display QR code in terminal (requires qrencode)
  -version                                 Show version
  -update                                  Check for updates and install from site
  -update-check                             Check for updates (runs automatically on terminal startup)
  -uninstall                               Remove brt from this system
  -help                                    Show this help

Examples:
  brt -ip public
  brt -ssl github.com
  brt -headers https://example.com
  brt -post https://httpbin.org/post -d 'hello=world'
  brt -killport 8080
  brt -run 'echo "hello";wait 2;echo "bye"'
  brt -weather "San Francisco"
  brt -image photo.jpg -x 120 -y 30
  brt -video clip.mp4
  brt -video https://example.com/video.mp4
  brt -video 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'
  brt -browse "python terminal hyperlinks"
  brt -doom
  brt -config
  brt -access serve

$(brt_print_install_hints)
EOF
}

main() {
  if [[ $# -gt 0 && "$1" != "-update-check" ]]; then
    brt_maybe_check_updates_async
  fi

  if [[ $# -eq 0 ]]; then
    brt_show_pending_update_notice
    usage
    exit 0
  fi

  case "$1" in
    -update-check|-update|-version|-v|-help|-h) ;;
    *) brt_show_pending_update_notice ;;
  esac

  local flag="$1"
  shift

  case "$flag" in
    -ip)           source "${BRT_LIB}/ip.sh";       brt_ip "$@" ;;
    -dns|-nslookup) source "${BRT_LIB}/dns.sh";    brt_dns "$@" ;;
    -portscan|-scan) source "${BRT_LIB}/portscan.sh"; brt_portscan "$@" ;;
    -ping)         source "${BRT_LIB}/ping.sh";     brt_ping "$@" ;;
    -whois)        source "${BRT_LIB}/whois.sh";    brt_whois "$@" ;;
    -traceroute|-trace) source "${BRT_LIB}/trace.sh"; brt_trace "$@" ;;
    -headers)      source "${BRT_LIB}/headers.sh";  brt_headers "$@" ;;
    -ssl)          source "${BRT_LIB}/ssl.sh";      brt_ssl "$@" ;;
    -reverse)      source "${BRT_LIB}/reverse.sh";  brt_reverse "$@" ;;
    -curl)         source "${BRT_LIB}/curl.sh";     brt_curl "$@" ;;
    -post)         source "${BRT_LIB}/post.sh";     brt_post "$@" ;;
    -edit)         source "${BRT_LIB}/edit.sh";     brt_edit "$@" ;;
    -json)         source "${BRT_LIB}/json.sh";     brt_json "$@" ;;
    -encode)       source "${BRT_LIB}/encode.sh";   brt_encode "$@" ;;
    -decode)       source "${BRT_LIB}/encode.sh";   brt_decode "$@" ;;
    -hash)         source "${BRT_LIB}/hash.sh";     brt_hash "$@" ;;
    -urlencode)    source "${BRT_LIB}/url.sh";      brt_urlencode "$@" ;;
    -urldecode)    source "${BRT_LIB}/url.sh";      brt_urldecode "$@" ;;
    -grep)         source "${BRT_LIB}/grep.sh";     brt_grep "$@" ;;
    -image|-img)   source "${BRT_LIB}/image.sh";    brt_image "$@" ;;
    -video|-play)  source "${BRT_LIB}/video.sh";    brt_video "$@" ;;
    -doom)         source "${BRT_LIB}/doom.sh";     brt_doom "$@" ;;
    -browse|-search) source "${BRT_LIB}/browse.sh";  brt_browse "$@" ;;
    -uuid)         source "${BRT_LIB}/uuid.sh";     brt_uuid "$@" ;;
    -pass|-password) source "${BRT_LIB}/pass.sh"; brt_pass "$@" ;;
    -run)          source "${BRT_LIB}/run.sh";      brt_run "$@" ;;
    -serve)        source "${BRT_LIB}/serve.sh";    brt_serve "$@" ;;
    -watch)        source "${BRT_LIB}/watch.sh";    brt_watch "$@" ;;
    -listen)       source "${BRT_LIB}/listen.sh";   brt_listen "$@" ;;
    -killport)     source "${BRT_LIB}/killport.sh"; brt_killport "$@" ;;
    -du)           source "${BRT_LIB}/du.sh";       brt_du "$@" ;;
    -extract)      source "${BRT_LIB}/extract.sh"; brt_extract "$@" ;;
    -sysinfo)      source "${BRT_LIB}/sysinfo.sh";  brt_sysinfo "$@" ;;
    -publickey)    source "${BRT_LIB}/publickey.sh"; brt_publickey "$@" ;;
    -timestamp)    source "${BRT_LIB}/timestamp.sh"; brt_timestamp "$@" ;;
    -timer)        source "${BRT_LIB}/timer.sh";    brt_timer "$@" ;;
    -calc)         source "${BRT_LIB}/calc.sh";     brt_calc "$@" ;;
    -env)          source "${BRT_LIB}/env.sh";      brt_env "$@" ;;
    -which-all)    source "${BRT_LIB}/which.sh";    brt_which_all "$@" ;;
    -access)       source "${BRT_LIB}/access.sh";   brt_access "$@" ;;
    -config)       brt_config "$@" ;;
    -speed)        source "${BRT_LIB}/speed.sh";    brt_speed "$@" ;;
    -weather)      source "${BRT_LIB}/weather.sh";  brt_weather "$@" ;;
    -qr)           source "${BRT_LIB}/qr.sh";       brt_qr "$@" ;;
    -update)       source "${BRT_LIB}/update.sh";   brt_update "$@" ;;
    -update-check)  source "${BRT_LIB}/update.sh";   brt_update_check "$@" ;;
    -uninstall)    source "${BRT_LIB}/uninstall.sh"; brt_uninstall "$@" ;;
    -version|-v)   brt_version_cmd "$@" ;;
    -help|-h)      usage ;;
    *)
      brt_error "Unknown command: ${flag}"
      echo "Run 'brt -help' for usage."
      exit 1
      ;;
  esac
}

main "$@"
