#!/bin/sh
# fxbot's one line, for a Mac, Linux, and Windows in WSL 2: curl -fsSL https://fxbot.sh/install.sh | sh
#
# It runs as you, not root. It unpacks the newest release's archive for this machine into ~/.fxbot, checked against
# the release's SHA256SUMS first, puts `fxbot` on your PATH, and starts fxbot. On Linux it asks once whether to set up
# the computer, which needs root once; under WSL 2 it asks whether to keep WSL running. Run again, it updates to the
# newest release, or finishes a broken install, and leaves your data alone. FXBOT_HOME, FXBOT_VERSION,
# FXBOT_RELEASES_URL, and FXBOT_DOWNLOADS_URL change where it installs and what from, for checks.
set -eu

say() { printf '%s\n' "$*"; }
die() {
  printf '\nfxbot install stopped: %s\n' "$*" >&2
  exit 1
}
# A question on the terminal, even though this script comes in on standard input. With no terminal, as when an agent
# runs it, the answer is no. WSL can attach a controlling terminal even when it redirects all three streams.
terminal() { [ -t 1 ] && (: </dev/tty) 2>/dev/null; }
yes() {
  terminal || return 1
  printf '%s [Y/n] ' "$1" >/dev/tty
  read -r answer </dev/tty || answer=n
  case $answer in [Nn]*) return 1 ;; *) return 0 ;; esac
}
sha256() { if command -v sha256sum >/dev/null; then sha256sum "$1"; else shasum -a 256 "$1"; fi | cut -d ' ' -f 1; }

[ "$(id -u)" -ne 0 ] || die "Run it as yourself, without sudo."

# The machine.
os=$(uname -s)
case $(uname -m) in
  x86_64 | amd64) cpu=x64 ;;
  arm64 | aarch64) cpu=arm64 ;;
  *) die "fxbot runs on x64 and arm64 CPUs, and this one is $(uname -m)." ;;
esac
wsl=""
case $os in
  Darwin)
    macos=$(sw_vers -productVersion)
    [ "${macos%%.*}" -ge 15 ] || die "fxbot needs macOS 15 or newer, and this Mac has $macos. Update macOS, then run this again."
    ;;
  Linux)
    case $(uname -r) in
      *Microsoft*) die "fxbot needs WSL 2, and this is WSL 1. In PowerShell: wsl --set-version ${WSL_DISTRO_NAME:-<distro>} 2" ;;
      *microsoft* | *WSL*) wsl=1 ;;
    esac
    glibc=$(getconf GNU_LIBC_VERSION 2>/dev/null | cut -d ' ' -f 2) || glibc=""
    [ -n "$glibc" ] || die "fxbot needs a Linux with glibc 2.36 or newer, and this one has another C library, such as Alpine's musl."
    minor=${glibc#*.}
    if [ "${glibc%%.*}" -lt 2 ] || { [ "${glibc%%.*}" -eq 2 ] && [ "${minor%%.*}" -lt 36 ]; }; then
      die "This Linux has glibc $glibc, and the app needs 2.36 or newer: Debian 12, Ubuntu 24.04, Fedora 37, or newer. Host fxbot with containers instead: curl -fsSL https://fxbot.sh/setup.sh | sudo bash"
    fi
    if [ -n "$wsl" ] && [ ! -d /run/systemd/system ]; then
      die "fxbot needs systemd, which is off in this WSL distro. Add these two lines to /etc/wsl.conf:
  [boot]
  systemd=true
then run 'wsl --shutdown' in PowerShell, open this distro again, and run the line again."
    fi
    ;;
  *) die "fxbot runs on a Mac and Linux, and on Windows in WSL 2. This is $os." ;;
esac
[ "$os" = Darwin ] && target=darwin-$cpu || target=linux-$cpu

# The archive.
home=${FXBOT_HOME:-$HOME/.fxbot}
releases=${FXBOT_RELEASES_URL:-https://api.github.com/repos/iammrduncan/fxbot/releases/latest}
downloads=${FXBOT_DOWNLOADS_URL:-https://github.com/iammrduncan/fxbot/releases/download}
version=${FXBOT_VERSION:-$(curl -fsSL "$releases" | sed -n 's/.*"tag_name": *"v\{0,1\}\([^"]*\)".*/\1/p' | head -n 1)}
version=${version#v}
[ -n "$version" ] || die "Couldn't find fxbot's newest release at $releases."
mkdir -p "$home/versions"
chmod 700 "$home"
if [ ! -f "$home/versions/$version/app/deploy/app/fxbot.ts" ]; then
  name=fxbot-$version-$target.tar.gz
  partial=$home/versions/.$version.partial
  rm -rf "$partial" && mkdir "$partial"
  say "Downloading fxbot $version for $target"
  curl -fSL --progress-bar "$downloads/v$version/$name" -o "$partial/$name" || die "Couldn't download $downloads/v$version/$name"
  curl -fsSL "$downloads/v$version/SHA256SUMS" -o "$partial/SHA256SUMS" || die "Couldn't download $version's SHA256SUMS."
  want=$(awk -v n="$name" '$2 == n || $2 == "*" n { print $1 }' "$partial/SHA256SUMS")
  if [ -z "$want" ] || [ "$want" != "$(sha256 "$partial/$name")" ]; then
    rm -rf "$partial"
    die "The download didn't match its checksum, so nothing was unpacked. Run the line again."
  fi
  tar -xzf "$partial/$name" -C "$partial"
  rm -rf "$home/versions/$version"
  mv "$partial/$version" "$home/versions/$version"
  rm -rf "$partial"
fi

# The command, which runs the current version's fxbot.ts on its own Node.
mkdir -p "$home/bin"
quoted=$(printf '%s' "$home" | sed "s/'/'\\\\''/g")
cat >"$home/bin/fxbot" <<EOF
#!/bin/sh
# fxbot's command: the current version's fxbot.ts, on that version's own Node.
FXBOT_HOME='$quoted'
export FXBOT_HOME
v=\$(cat "\$FXBOT_HOME/current") || exit 1
exec "\$FXBOT_HOME/versions/\$v/node/bin/node" "\$FXBOT_HOME/versions/\$v/app/deploy/app/fxbot.ts" "\$@"
EOF
chmod 755 "$home/bin/fxbot"
# What a check set, kept for the service: the port, the service's name, and where releases come from.
touch "$home/fxbot.env" && chmod 600 "$home/fxbot.env"
for setting in FXBOT_PORT FXBOT_SERVICE FXBOT_RELEASES_URL FXBOT_DOWNLOADS_URL FXBOT_EMBEDDER FXBOT_COMPUTER_NAME FXBOT_COMPUTER_VM FXBOT_LIMACTL FXBOT_COMPUTER_IDLE; do
  eval "value=\${$setting:-}"
  [ -z "$value" ] || grep -q "^$setting=" "$home/fxbot.env" || printf '%s=%s\n' "$setting" "$value" >>"$home/fxbot.env"
done

# A newer version for an fxbot that runs goes through its own update, with its backup and its way back.
if [ -f "$home/current" ] && [ "$(cat "$home/current")" != "$version" ] && "$home/bin/fxbot" status 2>/dev/null | grep -q ': running'; then
  "$home/bin/fxbot" update "$version"
else
  printf '%s\n' "$version" >"$home/current"
fi

# fxbot on PATH: a link in ~/.local/bin when that's on it, or one line in the shell's file.
case ":$PATH:" in
  *":$HOME/.local/bin:"*)
    mkdir -p "$HOME/.local/bin"
    ln -sf "$home/bin/fxbot" "$HOME/.local/bin/fxbot"
    ;;
  *)
    case $(basename "${SHELL:-sh}") in
      zsh) rc=${ZDOTDIR:-$HOME}/.zshrc ;;
      bash) [ "$os" = Darwin ] && rc=$HOME/.bash_profile || rc=$HOME/.bashrc ;;
      fish) rc=$HOME/.config/fish/conf.d/fxbot.fish ;;
      *) rc=$HOME/.profile ;;
    esac
    if ! grep -q "^# fxbot's command" "$rc" 2>/dev/null; then
      mkdir -p "$(dirname "$rc")"
      case $rc in
        *.fish) printf "# fxbot's command\nfish_add_path '%s'\n" "$home/bin" >>"$rc" ;;
        *) printf "\n# fxbot's command\nexport PATH='%s':\"\$PATH\"\n" "$quoted/bin" >>"$rc" ;;
      esac
    fi
    say "fxbot is on your PATH in new terminals. In this one, run: export PATH=\"$home/bin:\$PATH\""
    ;;
esac

# On Linux and WSL 2, the computer, which needs root once. Not in a container, which may not allow it.
if [ "$os" = Linux ]; then
  inside=""
  if [ -z "$wsl" ]; then
    inside=$(systemd-detect-virt --container 2>/dev/null) || inside=""
    [ "$inside" != none ] || inside=""
    if [ -z "$inside" ] && [ -f /run/.containerenv ]; then inside=podman; fi
    if [ -z "$inside" ] && [ -f /.dockerenv ]; then inside=docker; fi
  fi
  if [ -n "$inside" ]; then
    say "fxbot runs here, but its computer needs a machine or a VM of its own, not a container ($inside). fxbot computer on can try anyway."
  elif [ -d "/var/lib/${FXBOT_COMPUTER_NAME:-fxbot-computer}" ]; then
    :
  elif terminal; then
    say ""
    say "fxbot's computer, where bots run commands and a browser, needs root once: it installs podman,"
    say "adds a user for the computers, and a firewall that keeps them off this machine and your network."
    if yes "Set it up now? It asks for your password."; then
      sudo bash "$home/versions/$version/computer/setup.sh" --user "$(id -un)" ${FXBOT_COMPUTER_NAME:+--name "$FXBOT_COMPUTER_NAME"} ||
        say "The computer's setup didn't finish. To try again: fxbot computer on"
    else
      say "To set up the computer later: fxbot computer on"
    fi
  else
    say "The computer needs root once. To set it up: fxbot computer on"
  fi
fi

# Under WSL 2, Windows' part: WSL keeps running with no window open, and starts when you sign in to Windows.
# From C:, where cmd.exe runs without a word about the folder, when WSL mounts it there.
win() { (cd /mnt/c 2>/dev/null || :; cmd.exe /c "echo %$1%" 2>/dev/null </dev/null | tr -d '\r'); }
psquote() { printf '%s' "$1" | sed "s/'/''/g"; }
key() { # .wslconfig, section, key, marker
  if grep -qi "^[[:space:]]*$3[[:space:]]*=" "$1" 2>/dev/null; then
    grep -qi "^[[:space:]]*$3[[:space:]]*=[[:space:]]*-1" "$1" || say "Your .wslconfig sets $3 already, so it stays as it is."
    return
  fi
  if grep -qi "^\[$2\]" "$1" 2>/dev/null; then
    awk -v section="[$2]" -v mark="$4" -v line="$3=-1" '
      { print; l = $0; cr = sub(/\r$/, "", l) ? "\r" : "" }
      tolower(l) == section && !done { print mark cr; print line cr; done = 1 }' "$1" >"$1.fxbot"
    cat "$1.fxbot" >"$1" && rm -f "$1.fxbot"
  else
    printf '\n[%s]\n%s\n%s=-1\n' "$2" "$4" "$3" >>"$1"
  fi
}
if [ -n "$wsl" ] && [ -n "${WSL_DISTRO_NAME:-}" ] && command -v cmd.exe >/dev/null && command -v wslpath >/dev/null && command -v powershell.exe >/dev/null; then
  profile=$(wslpath -u "$(win USERPROFILE)" 2>/dev/null) || profile=""
  service=$(sed -n 's/^FXBOT_SERVICE=//p' "$home/fxbot.env" | head -n 1)
  service=${FXBOT_SERVICE:-${service:-fxbot}}
  say ""
  say "Windows stops WSL soon after its last window closes, and fxbot with it."
  say "Keeping it running adds two settings to .wslconfig that apply to every WSL distro."
  if [ -d "$profile" ] && yes "Keep WSL running and start it when you sign in to Windows?"; then
    mark="# Added by fxbot's install ($WSL_DISTRO_NAME/$service): WSL keeps running with no window open."
    if [ ! -f "$home/wsl-autostart" ]; then
      printf '%s\n' "$mark" >"$home/wsl-autostart"
      [ -e "$profile/.wslconfig" ] || printf '%s\n' created-config >>"$home/wsl-autostart"
    fi
    key "$profile/.wslconfig" general instanceIdleTimeout "$mark"
    key "$profile/.wslconfig" wsl2 vmIdleTimeout "$mark"
    powershell.exe -NoProfile -NonInteractive -Command "
      \$ErrorActionPreference = 'Stop'
      \$path = Join-Path ([Environment]::GetFolderPath('Startup')) '$(psquote "$service.lnk")'
      \$link = (New-Object -ComObject WScript.Shell).CreateShortcut(\$path)
      if ((Test-Path -LiteralPath \$path) -and \$link.Description -cne '$(psquote "$mark")') { exit 1 }
      \$link.TargetPath = Join-Path \$env:SystemRoot 'System32\wsl.exe'
      # wsl.exe looks up the literal distro argument, including any double quotes.
      \$link.Arguments = '-d $(psquote "$WSL_DISTRO_NAME") --exec true'
      \$link.WindowStyle = 7
      \$link.Description = '$(psquote "$mark")'
      \$link.Save()" </dev/null >/dev/null 2>&1 ||
      say "Couldn't add the shortcut that starts WSL when you sign in."
    say "WSL reads the new settings at its next start: after a restart, or 'wsl --shutdown' in PowerShell."
  else
    say "fxbot runs while a WSL window is open."
  fi
fi

say ""
exec "$home/bin/fxbot"
