#!/bin/sh
# flie 0.4.0: macOS Apple Silicon. Integrity checksum, not publisher signing.
# No startup files, credentials, sudo, or macOS security settings are changed.
# The complete function must parse before anything mutates the filesystem.
install_flie() {
  set -eu
  # The CLI's colour roles (cli/src/style.rs), and its gate: each stream is styled
  # only when it is a terminal and NO_COLOR, TERM=dumb and CI all leave it alone.
  # Otherwise every role is empty and each line is the bytes it always was.
  good='' caution='' strong='' dim='' off='' ebad='' ecaution='' eoff=''
  if [ -z "${NO_COLOR-}" ] && [ "${TERM-}" != dumb ] && [ -z "${CI-}" ]; then
    esc=$(printf '\033')
    if [ -t 1 ]; then good="$esc[32m" caution="$esc[33m" strong="$esc[1m" dim="$esc[2m" off="$esc[0m"; fi
    if [ -t 2 ]; then ebad="$esc[31m" ecaution="$esc[33m" eoff="$esc[0m"; fi
  fi
  die() { printf '%s\n' "${ebad}flie install: $*${eoff}" >&2; exit 1; }
  [ "$#" -eq 0 ] || die 'No installation flags are supported.'
  [ "$(uname -s)" = Darwin ] || die 'Only macOS Apple Silicon (Darwin arm64) is supported.'
  [ "$(uname -m)" = arm64 ] || die 'Only Apple Silicon arm64 is supported; Intel/Rosetta is not verified.'
  home=${HOME-}
  case "$home" in /) die 'HOME must name your user directory.';; /*) ;; *) die 'HOME must be an absolute user directory.';; esac
  [ -d "$home" ] && [ ! -L "$home" ] || die 'HOME must be a real directory.'
  destination="$home/.local/bin"
  target="$destination/flie"
  check_target() {
    for directory in "$home/.local" "$destination"; do
      [ ! -L "$directory" ] || die 'Refusing a symlink installation directory.'
      if [ -e "$directory" ] && [ ! -d "$directory" ]; then die 'Installation directory is not a directory.'; fi
    done
    [ ! -L "$target" ] || die 'Refusing to replace a symlink at ~/.local/bin/flie.'
    if [ -e "$target" ] && { [ ! -f "$target" ] || [ ! -x "$target" ]; }; then
      die 'Existing ~/.local/bin/flie must be a regular executable file.'
    fi
  }
  check_target
  for tool in curl shasum tar file mktemp chmod cp mv mkdir rmdir rm; do command -v "$tool" >/dev/null 2>&1 || die "Required command missing: $tool"; done
  umask 077
  work=''
  staged=''
  lock_owned=''
  lock="$destination/.flie-install.lock"
  trap 'if [ -n "$staged" ]; then rm -f "$staged"; fi; if [ -n "$work" ]; then rm -rf "$work"; fi; if [ -n "$lock_owned" ]; then rmdir "$lock"; fi' 0
  trap 'exit 1' HUP INT TERM
  mkdir -p "$destination"
  if mkdir "$lock" 2>/dev/null; then lock_owned=yes; else
    die 'Another install is running, or an interrupted install left ~/.local/bin/.flie-install.lock. Wait and retry. Only after confirming no installer is running, remove that empty directory with rmdir.'
  fi
  work=$(mktemp -d) || die 'Could not create a temporary directory.'
  archive="$work/release.tar.gz"
  origin='https://flie.sh'
  folder='flie-aarch64-apple-darwin'
  expected='cbc7064cbb4ddcba1e2324fa9b644a50e0de25cb7d885a59049b00209fb1699b'
  expected_binary='36339f48ed4390367a96eaacf972d9557c149be54ed9392afd239c4090e8862d'
  curl -fsSL --connect-timeout 15 --max-time 180 --output "$archive" 'https://flie.sh/downloads/flie-0.4.0-macos-arm64-cbc7064cbb4d.tar.gz' || die 'Download failed; existing installation was preserved.'
  printf '%s  %s\n' "$expected" "$archive" | shasum -a 256 -c - >/dev/null 2>&1 || die 'Archive checksum mismatch; existing installation was preserved.'
  tar -xzf "$archive" -C "$work" "$folder/flie" "$folder/README.txt" || die 'Extraction failed; existing installation was preserved.'
  binary="$work/$folder/flie"
  [ -f "$binary" ] && [ ! -L "$binary" ] || die 'Archive did not contain a regular CLI binary.'
  printf '%s  %s\n' "$expected_binary" "$binary" | shasum -a 256 -c - >/dev/null 2>&1 || die 'Binary checksum mismatch; existing installation was preserved.'
  case "$(file -b "$binary")" in 'Mach-O 64-bit executable arm64'*) ;; *) die 'Downloaded binary is not macOS arm64.';; esac
  chmod 755 "$binary"
  "$binary" --help >/dev/null || die 'CLI validation failed. Review macOS trust prompts; no security bypass was attempted.'
  check_target
  mkdir -p "$destination"
  staged=$(mktemp "$destination/.flie-install.XXXXXX") || die 'Could not stage the installation.'
  cp "$binary" "$staged" && chmod 755 "$staged" || die 'Could not stage the executable; existing installation was preserved.'
  check_target
  mv -f "$staged" "$target" || die 'Atomic installation failed.'
  staged=''
  printf '%s\n' "${good}"'Installed flie 0.4.0 to ~/.local/bin/flie.'"${off} ${dim}"'Re-run this installer to update or reinstall; your login and settings are preserved.'"${off}"
  resolved=$(command -v flie 2>/dev/null || :)
  if [ -n "$resolved" ] && [ "$resolved" != "$target" ]; then
    printf '%s\n' "${ecaution}Warning: this shell resolves flie to $resolved before the installed binary. Review PATH or the other installation before running the commands below.${eoff}" >&2
  fi
  # The origin this installer was fetched from becomes the saved default server, so
  # the first command a person or an agent runs needs no flag to reach it. Settings
  # only: credentials are never read or written here.
  saved=''
  if "$target" config set-server "$origin" >/dev/null 2>&1; then saved=yes; fi
  if [ -n "$saved" ]; then
    printf '%s\n' "${dim}Saved $origin as your server.${off}"
  else
    printf '%s\n' "${ecaution}Could not save $origin as your server; the login below names it explicitly. Repair saved settings with flie config reset.${eoff}" >&2
  fi
  # No startup file is edited, here or ever. Where the directory is not on PATH the
  # one line that puts it there for this terminal is printed, in the syntax of the
  # login shell $SHELL names.
  case ":${PATH-}:" in *":$destination:"*) ;; *)
    printf '%s\n' '' "${caution}"'~/.local/bin is not on PATH. Run this line first (no startup file was changed):'"${off}"
    case "${SHELL-}" in
      */fish|fish) printf '%s\n' "  ${strong}"'set -gx PATH "$HOME/.local/bin" $PATH'"${off}";;
      *) printf '%s\n' "  ${strong}"'export PATH="$HOME/.local/bin:$PATH"'"${off}";;
    esac;;
  esac
  printf '%s\n' '' 'Then:'
  if [ -n "$saved" ]; then
    printf '%s\n' "  ${strong}flie login${off}"
  else
    printf '%s\n' "  ${strong}"'flie login --server '\''https://flie.sh'\'''"${off}"
  fi
  printf '%s\n' "  ${strong}flie skill install --agent claude|codex|cursor${off}" "${dim}Reload the agent after installing its skill.${off}"
  printf '%s\n' '' 'Or paste this to your agent:' '  1. Run: curl -fsSL '\''https://flie.sh/install.sh'\'' | sh' '  2. Ensure `flie` resolves in a new shell; if it does not, add ~/.local/bin to PATH in the shell startup file and report the change you made.' '  3. Run: flie login; it prints a link and waits. Give that link to the person to open in their browser on this laptop — do not fetch it yourself — and keep the command waiting until it prints Signed in.'
  # The command is not the only route: a host reaches the same account by the
  # server's URL with nothing installed. Say so here, where a person who has just
  # installed it is being told what to do next, and point at the page that carries
  # the registration line for each host rather than repeating it in a shell script.
  # The hosts it names are the reference source's, so none can be left out here.
  printf '%s\n' '' "${dim}"'An agent can also reach flie with nothing installed, by registering https://flie.sh/mcp with its host.'"${off}" "${dim}"'The registration lines for Claude Code, Codex and Cursor are on https://flie.sh/.'"${off}"

}
install_flie "$@"
