#!/bin/sh
# Wagahai installer — https://wagahai.org
#
#   curl -fsSL https://wagahai.org/install.sh | sh
#
# Installs the wagahai client to ~/.local/bin, checksum-verified.
# Free, experimental; probably doesn't work. We use it daily anyway.
set -eu

say() { printf '%s\n' "$*"; }

os=$(uname -s); arch=$(uname -m)
case "$os-$arch" in
  Darwin-arm64) target="aarch64-apple-darwin" ;;
  *)
    say "wagahai is built for Apple Silicon macOS today; $os/$arch isn't — yet."
    say "Tell us to hurry: info@katayama.dev"
    exit 1 ;;
esac

v="0.1.1"
base="https://wagahai.org/dl"
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT

say "fetching wagahai v$v ($target)…"
curl -fsSL "$base/wagahai-v$v-$target.tar.gz" -o "$tmp/wagahai.tgz"
curl -fsSL "$base/SHA256SUMS" -o "$tmp/SHA256SUMS"
want=$(grep "wagahai-v$v-$target.tar.gz" "$tmp/SHA256SUMS" | cut -d' ' -f1)
got=$(shasum -a 256 "$tmp/wagahai.tgz" | cut -d' ' -f1)
[ "$want" = "$got" ] || { say "✗ checksum mismatch — not installing."; exit 1; }

tar -xzf "$tmp/wagahai.tgz" -C "$tmp"
mkdir -p "$HOME/.local/bin"
install -m 755 "$tmp/wagahai" "$HOME/.local/bin/wagahai"
say "✓ installed: ~/.local/bin/wagahai (v$v, checksum verified)"

# The ink year: the seventy-two microseasons the sidebar's corner turns
# through, a cache beside the mail — twelve of them ride in the binary,
# the rest arrive here. Re-run this script for a newer year.
ink="${XDG_DATA_HOME:-$HOME/.local/share}/wagahai/ink"
curl -fsSL "$base/wagahai-ink.tar.gz" -o "$tmp/ink.tgz"
want=$(grep " wagahai-ink.tar.gz" "$tmp/SHA256SUMS" | cut -d' ' -f1)
got=$(shasum -a 256 "$tmp/ink.tgz" | cut -d' ' -f1)
if [ "$want" != "$got" ]; then
  say "  (the ink year's checksum did not match — the corner keeps its twelve)"
elif ! mkdir -p "$tmp/ink" "$(dirname "$ink")" || ! tar -xzf "$tmp/ink.tgz" -C "$tmp/ink"; then
  say "  (the ink year would not unpack — the corner keeps its twelve)"
else
  rm -f "$tmp/ink/.sha256" && printf '%s\n' "$want" > "$tmp/ink/.sha256"
  # the old cache steps aside only once the new one is beside it, and goes
  # only once the new one has its name
  mv "$tmp/ink" "$ink.new.$$"
  [ -e "$ink" ] && mv "$ink" "$ink.old.$$"
  mv "$ink.new.$$" "$ink" && rm -rf "$ink.old.$$"
  say "✓ the ink year: $(ls "$ink"/*.png | wc -l | tr -d ' ') pictures for the corner"
fi
case ":$PATH:" in
  *":$HOME/.local/bin:"*) ;;
  *) say "  (add ~/.local/bin to your PATH)" ;;
esac

say ""
say "Meet the cat first — no account, no setup, a fully fictional mailbox:"
say ""
say "    wagahai --demo"
say ""
say "Real mail wants the daemon on an always-on machine, reached over ssh."
say "Early access and instructions: info@katayama.dev · https://wagahai.org"
