#!/bin/sh
# Install dayline.
#
#   curl -fsSL https://dayline.ai/install.sh | sh
#
# It downloads the static binaries for your platform, checks the sha256
# against the published manifest, and unpacks it into ~/.dayline/bin. No node,
# no sudo, no compiler, nothing written outside $DAYLINE_HOME.
#
# To upgrade, run `dayline update` (CLI 0.163.0 and newer reads the receipt
# this writes and updates this copy in place) or just re-run this installer.
# Either replaces what is there and leaves everything else in $DAYLINE_HOME
# alone.
#
# Environment:
#   DAYLINE_HOME          install root (default ~/.dayline); binaries go in bin/
#   DAYLINE_INSTALL_BASE  where to fetch the manifest and tarballs from
#
# Read it before you pipe it to a shell. That is the point of keeping it this
# short — it is ~150 lines because we ship a static Rust binary and need no
# runtime bootstrap at all.
set -eu

base="${DAYLINE_INSTALL_BASE:-https://dayline.ai}"
home="${DAYLINE_HOME:-$HOME/.dayline}"
prefix="$home/bin"
receipt="$home/install.json"

die() { echo "dayline install: $*" >&2; exit 1; }
say() { echo "$*"; }

# --- platform ----------------------------------------------------------------
# Fail by name rather than download a binary for the wrong machine: npm's
# os/cpu gates did this for us and nothing does it here but this case.
os="$(uname -s)"
arch="$(uname -m)"
case "$os/$arch" in
  Darwin/arm64)          target=darwin-arm64 ;;
  Linux/x86_64)          target=linux-x64 ;;
  CYGWIN*/*|MINGW*/*|MSYS*/*)
    die "Windows is not a published target — no dayline binary is built for it. Nothing was installed." ;;
  *)
    die "no published dayline binary for $os $arch. Published targets: darwin-arm64, linux-x64. Nothing was installed." ;;
esac

for tool in curl tar; do
  command -v "$tool" >/dev/null 2>&1 || die "$tool is required and was not found"
done

sha256_of() {
  if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1
  elif command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1
  elif command -v openssl >/dev/null 2>&1; then openssl dgst -sha256 "$1" | sed 's/.*= *//'
  else die "no sha256 tool found (sha256sum, shasum or openssl). Refusing to install unverified bytes."
  fi
}

# --- an existing receipt is read, never guessed at ---------------------------
# A receipt that exists but cannot be read means something else owns this
# directory, or a previous install was interrupted mid-write. Either way
# overwriting it would leave `dayline update` (which will read this file to
# learn its channel) believing something untrue, so refuse and say so.
if [ -f "$receipt" ]; then
  grep -q '"schemaVersion"' "$receipt" && grep -q '"channel"' "$receipt" \
    || die "$receipt exists but is not a dayline install receipt. Inspect it, then move it aside and re-run. Nothing was installed."
fi

# The staging directory is a child of $DAYLINE_HOME, not $TMPDIR, and that is
# load-bearing rather than tidiness. The install below is `mv`, i.e. rename(2),
# which is atomic — and safe to run over a binary that is currently executing,
# because the running image holds the inode — only *within one filesystem*.
# Across filesystems mv degrades to open/truncate/copy/unlink, which is neither:
# on Linux, where /tmp is routinely tmpfs and so a different device from $HOME,
# opening the running `dayline` for writing is ETXTBSY. Re-running this
# installer while the daemon is up would then fail partway, having already
# truncated one binary. Staging beside the destination makes the rename real.
mkdir -p "$home"
tmp="$(mktemp -d "$home/.install.XXXXXX")"
trap 'rm -rf "$tmp"' EXIT

# --- manifest ----------------------------------------------------------------
# Parsed with sed, not jq and certainly not node: this installer's whole claim
# is that it needs no runtime, and requiring jq would put a dependency in front
# of the install we are trying to make dependency-free. The manifest is written
# by scripts/publish-cli-tarballs.sh in a fixed shape, so a flatten-then-slice
# parse is reading our own format rather than parsing JSON in general.
say "fetching $base/cli/latest.json"
curl -fsSL "$base/cli/latest.json" -o "$tmp/latest.json" \
  || die "could not read $base/cli/latest.json"

blob="$(tr -d ' \t\n' < "$tmp/latest.json")"
version="$(printf '%s' "$blob" | sed -n 's/.*"version":"\([^"]*\)".*/\1/p')"
[ -n "$version" ] || die "no version in the manifest at $base/cli/latest.json"

case "$blob" in
  *"\"$target\":{"*) ;;
  *) die "the manifest for dayline $version publishes no $target build. Nothing was installed." ;;
esac
entry="${blob#*\"$target\":\{}"
entry="${entry%%\}*}"
url="$(printf '%s' "$entry" | sed -n 's/.*"url":"\([^"]*\)".*/\1/p')"
want="$(printf '%s' "$entry" | sed -n 's/.*"sha256":"\([^"]*\)".*/\1/p')"
[ -n "$url" ] && [ -n "$want" ] || die "the manifest entry for $target has no url or sha256"

# --- download and verify before unpacking ------------------------------------
# There is no registry doing integrity for this channel. The archive is not
# opened until its digest matches the manifest's.
say "downloading dayline $version ($target)"
curl -fsSL "$url" -o "$tmp/dayline.tar.gz" || die "could not download $url"
got="$(sha256_of "$tmp/dayline.tar.gz")"
[ "$got" = "$want" ] || die "checksum mismatch for $url
  expected $want
  got      $got
Nothing was installed."

mkdir -p "$tmp/unpack"
tar -tzf "$tmp/dayline.tar.gz" > "$tmp/members" || die "could not list archive"
awk '($0 != "dayline" && $0 != "dayline-daemon" && $0 != "storefs") || seen[$0]++ { bad=1 } END { exit bad || !seen["dayline"] }' "$tmp/members" \
  || die "the archive has missing, unexpected or duplicate binaries. Nothing was installed."
tar -tvzf "$tmp/dayline.tar.gz" > "$tmp/types" || die "could not inspect archive"
awk 'substr($0,1,1) != "-" { bad=1 } END { exit bad }' "$tmp/types" \
  || die "the archive must contain only regular files. Nothing was installed."
tar -xzf "$tmp/dayline.tar.gz" -C "$tmp/unpack"

# --- install -----------------------------------------------------------------
# Every binary is unpacked and made executable before any is moved, so a
# failure here cannot leave one new binary beside one old one — an install that
# half-landed is worse than one that did not land at all.
#
exes="dayline"
[ -f "$tmp/unpack/dayline-daemon" ] && exes="$exes dayline-daemon"
cli_dest="$prefix/dayline"
receipt_exe=""
# Keep the NixOS launcher that supplies Bun's native-library paths.
if [ -f "$cli_dest" ] && [ ! -L "$cli_dest" ] && [ "$(head -c 2 "$cli_dest")" = '#!' ]; then
  grep -q 'dayline\.bin' "$cli_dest" || die "$cli_dest is an unrecognized launcher. Nothing was installed."
  cli_dest="$prefix/dayline.bin"
  receipt_exe="$cli_dest"
fi
for exe in $exes; do
  [ -s "$tmp/unpack/$exe" ] || die "the archive is missing $exe or it is empty. Nothing was installed."
  dest="$prefix/$exe"
  [ "$exe" != dayline ] || dest="$cli_dest"
  [ ! -d "$dest" ] || die "$dest is a directory. Nothing was installed."
  chmod +x "$tmp/unpack/$exe"
done
mkdir -p "$prefix"
# mv can fall back to copy/truncate across devices. Refuse before replacing
# anything when bin/ points at another filesystem.
if [ "$os" = Darwin ]; then
  staging_device="$(stat -f %d "$tmp/unpack")"
  prefix_device="$(stat -f %d "$prefix/.")"
else
  staging_device="$(stat -c %d "$tmp/unpack")"
  prefix_device="$(stat -c %d "$prefix/.")"
fi
[ "$staging_device" = "$prefix_device" ] || die "staging and install prefix must be on one filesystem. Nothing was installed."
for exe in $exes; do
  dest="$prefix/$exe"
  [ "$exe" != dayline ] || dest="$cli_dest"
  mv -f "$tmp/unpack/$exe" "$dest"
done

# --- receipt -----------------------------------------------------------------
# `binary` is the field `dayline update` will compare against its own
# current_exe() to decide whether this receipt describes the copy that is
# actually running. Written to a temp file and renamed, so a receipt is never
# half-written.
cat > "$receipt.tmp.$$" <<JSON
{
  "schemaVersion": 1,
  "channel": "tarball",
  "version": "$version",
  "target": "$target",
  "binary": "$prefix/dayline",
  "exe": "$receipt_exe",
  "prefix": "$prefix",
  "installed_at": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
JSON
mv -f "$receipt.tmp.$$" "$receipt"

say ""
say "dayline $version installed to $prefix"

case ":$PATH:" in
  *":$prefix:"*) ;;
  *)
    say ""
    say "$prefix is not on your PATH. Add it:"
    say ""
    say "    export PATH=\"$prefix:\$PATH\""
    ;;
esac


say ""
say "Next: dayline service install   (runs the daemon under launchd/systemd)"
say ""
say "To upgrade: \`dayline update\` — it reads the receipt this wrote and"
say "replaces these binaries in place, rather than installing a second copy"
say "through npm or bun. Re-running this installer does the same thing."
say ""
say "One thing npm gives that this does not: the ACP adapter. If you set"
say "DAYLINE_NATIVE_ACP=off, also run:"
say ""
say "    npm i -g @agentclientprotocol/claude-agent-acp"
