#!/bin/sh
# Emisteme installer for Linux x86_64 and macOS on Apple silicon.
#
#   curl -fsSL https://emisteme.com/install.sh | sh
#   curl -fsSL https://emisteme.com/install.sh | sh -s -- --dry-run
#
# It reads the preview manifest (latest.json), picks the package for this system
# (pacman, apt, dnf or zypper; an AppImage in ~/.local/bin otherwise; Emisteme.app in
# /Applications on macOS), checks its SHA-256 against the manifest and installs it.
# It never runs as root itself: sudo is asked only for the package manager (and for
# /Applications when it is not writable).
set -eu

MANIFEST_URL=${EMISTEME_MANIFEST:-https://downloads.emisteme.com/preview/latest.json}
OS_RELEASE=${EMISTEME_OS_RELEASE:-/etc/os-release}
APPLICATIONS_DIR=${EMISTEME_APPLICATIONS_DIR:-/Applications}
BIN_DIR=${EMISTEME_BIN_DIR:-$HOME/.local/bin}
STATE_FILE=${XDG_DATA_HOME:-$HOME/.local/share}/emisteme/install-state

usage() {
  cat <<'EOF'
Emisteme installer

Usage: install.sh [option]

  (no option)   Install or update Emisteme from the latest preview
  --dry-run     Show what would be downloaded and installed, change nothing
  --version     Print the version that would be installed
  --uninstall   Remove what this script installed
  --help        Show this help

Supported: Linux x86_64 (pacman, apt, dnf, zypper, or an AppImage in ~/.local/bin)
and macOS on Apple silicon (Emisteme.app in /Applications).
Environment: EMISTEME_MANIFEST overrides the manifest URL.
EOF
}

if [ -t 1 ]; then
  BOLD=$(printf '\033[1m') BLUE=$(printf '\033[34m') GREEN=$(printf '\033[32m')
  RED=$(printf '\033[31m') DIM=$(printf '\033[2m') RESET=$(printf '\033[0m')
else
  BOLD='' BLUE='' GREEN='' RED='' DIM='' RESET=''
fi

step() { printf '%s→%s%s\n' "$BLUE" "$RESET" "$*"; }
good() { printf '%s→%s%s\n' "$GREEN" "$*" "$RESET"; }
note() { printf '%s%s%s\n' "$DIM" "$*" "$RESET"; }
die() {
  printf '%s✗ %s%s\n' "$RED" "$*" "$RESET" >&2
  exit 1
}

MODE=install
case ${1:-} in
  '') ;;
  --dry-run) MODE=dry-run ;;
  --version) MODE=version ;;
  --uninstall) MODE=uninstall ;;
  -h | --help)
    usage
    exit 0
    ;;
  *)
    usage >&2
    exit 2
    ;;
esac
[ $# -le 1 ] || {
  usage >&2
  exit 2
}

if [ "$(id -u)" = 0 ]; then
  die "Do not run this script as root. Run it as your user; it asks for sudo only for the package manager."
fi

# Runs a command as root: sudo is used only here, for the install step.
as_root() {
  command -v sudo >/dev/null 2>&1 || die "sudo is required to install the package with $PKG_TOOL."
  sudo "$@"
}

state_get() {
  [ -f "$STATE_FILE" ] || return 0
  sed -n "s/^$1=//p" "$STATE_FILE" | head -n 1
}

# ---- Uninstall --------------------------------------------------------------
if [ "$MODE" = uninstall ]; then
  printf '%sEmisteme installer%s\n' "$BOLD" "$RESET"
  kind=$(state_get kind)
  target=$(state_get target)
  [ -n "$kind" ] || die "Nothing to uninstall: this script has not installed Emisteme for this user."
  case $kind in
    pacman)
      PKG_TOOL=pacman
      step "Removing the emisteme package with pacman; sudo asks for your password"
      as_root pacman -R --noconfirm "$target"
      ;;
    deb)
      PKG_TOOL=apt-get
      step "Removing the $target package with apt-get; sudo asks for your password"
      as_root apt-get remove -y "$target"
      ;;
    rpm)
      PKG_TOOL=$(state_get tool)
      step "Removing the $target package with $PKG_TOOL; sudo asks for your password"
      if [ "$PKG_TOOL" = zypper ]; then
        as_root zypper --non-interactive remove "$target"
      else
        as_root dnf remove -y "$target"
      fi
      ;;
    appimage)
      step "Removing $target"
      rm -f "$target"
      ;;
    app)
      step "Removing $target"
      if [ -w "$(dirname "$target")" ]; then
        rm -rf "$target"
      else
        PKG_TOOL='rm'
        note "$(dirname "$target") is not writable by you; sudo asks for your password"
        as_root rm -rf "$target"
      fi
      ;;
    *) die "Unknown install record in $STATE_FILE." ;;
  esac
  rm -f "$STATE_FILE"
  printf '%s✓Emisteme is uninstalled.%s\n' "$GREEN$BOLD" "$RESET"
  note "Your notes and planning stay in your data folder."
  exit 0
fi

# ---- System -----------------------------------------------------------------
os=$(uname -s)
arch=$(uname -m)
case $os in
  Linux)
    case $arch in
      x86_64 | amd64) ;;
      *) die "Linux $arch is not supported yet: Emisteme ships for Linux x86_64 only. Nothing was downloaded." ;;
    esac
    platform=linux-x86_64
    distro=''
    if [ -r "$OS_RELEASE" ]; then
      distro=$(sed -n 's/^NAME=//p' "$OS_RELEASE" | head -n 1 | tr -d '"')
    fi
    system="Linux x86_64${distro:+, $distro}"
    if command -v pacman >/dev/null 2>&1; then
      kind=pacman PKG_TOOL=pacman label="Arch package"
    elif command -v apt-get >/dev/null 2>&1; then
      kind=deb PKG_TOOL=apt-get label="Debian package"
    elif command -v dnf >/dev/null 2>&1; then
      kind=rpm PKG_TOOL=dnf label="RPM package"
    elif command -v zypper >/dev/null 2>&1; then
      kind=rpm PKG_TOOL=zypper label="RPM package"
    else
      kind=appimage PKG_TOOL='' label="AppImage"
    fi
    ;;
  Darwin)
    # Under Rosetta, uname reports x86_64 on an Apple silicon Mac.
    if [ "$arch" != arm64 ] && [ "$(sysctl -n hw.optional.arm64 2>/dev/null || true)" != 1 ]; then
      die "Intel Macs are not supported: Emisteme ships for Apple silicon only. Nothing was downloaded."
    fi
    platform=darwin-aarch64
    system="macOS $(sw_vers -productVersion 2>/dev/null || echo), Apple silicon"
    kind=app PKG_TOOL='' label="Emisteme.app"
    ;;
  *) die "$os is not supported by this script. See https://emisteme.com/download. Nothing was downloaded." ;;
esac

# ---- Manifest ---------------------------------------------------------------
tmp=$(mktemp -d "${TMPDIR:-/tmp}/emisteme-install.XXXXXX")
trap 'rm -rf "$tmp"' EXIT
trap 'exit 130' INT TERM

curl -fsSL -o "$tmp/latest.json" "$MANIFEST_URL" || die "Could not read the manifest at $MANIFEST_URL."
# latest.json holds flat objects only: one object per line once braces become newlines.
awk '{ gsub(/[{}]/, "\n"); printf "%s ", $0 }' "$tmp/latest.json" >"$tmp/objects"
version=$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$tmp/objects" | head -n 1)
[ -n "$version" ] || die "The manifest at $MANIFEST_URL has no version."

if [ "$MODE" = version ]; then
  printf '%s\n' "$version"
  exit 0
fi

# Prints "name<TAB>size<TAB>sha256<TAB>url" for the file of this platform and kind.
awk -v platform="$platform" -v kind="$kind" '
  function field(key,   re) {
    re = "\"" key "\"[ \t]*:[ \t]*(\"[^\"]*\"|[0-9]+)"
    if (!match($0, re)) return ""
    v = substr($0, RSTART, RLENGTH)
    sub(/^"[^"]*"[ \t]*:[ \t]*/, "", v)
    gsub(/"/, "", v)
    return v
  }
  field("platform") == platform && field("kind") == kind {
    printf "%s\t%s\t%s\t%s\n", field("name"), field("size"), field("sha256"), field("url")
    exit
  }' "$tmp/objects" >"$tmp/file"
IFS=$(printf '\t') read -r name size sha url <"$tmp/file" || true
[ -n "${url:-}" ] && [ -n "${sha:-}" ] || die "The manifest has no $kind package for $platform in $version."
size_mb=$(awk -v s="${size:-0}" 'BEGIN { printf "%.1f", s / 1048576 }')

printf '%sEmisteme installer%s\n' "$BOLD" "$RESET"
step "$system"
step "Latest preview: $version"

case $kind in
  pacman) pkg_name=emisteme ;;
  deb) pkg_name=emisteme ;;
  rpm) pkg_name=Emisteme ;;
  appimage) pkg_name=$BIN_DIR/emisteme ;;
  app) pkg_name=$APPLICATIONS_DIR/Emisteme.app ;;
esac

if [ "$(state_get version)" = "$version" ] && [ "$(state_get kind)" = "$kind" ]; then
  case $kind in
    appimage | app) present=$([ -e "$pkg_name" ] && echo y || echo n) ;;
    *) present=y ;;
  esac
  if [ "$present" = y ]; then
    good "Emisteme $version is already up to date."
    exit 0
  fi
fi

if [ "$MODE" = dry-run ]; then
  step "Would download $label ($size_mb MB): $url"
  step "Would check its SHA-256 against latest.json: $sha"
  case $kind in
    pacman) step "Would install with: sudo pacman -U --noconfirm $name" ;;
    deb) step "Would install with: sudo apt-get install -y ./$name" ;;
    rpm) step "Would install with: sudo $PKG_TOOL install $name" ;;
    appimage) step "Would install to $pkg_name" ;;
    app) step "Would move Emisteme.app to $APPLICATIONS_DIR and remove its quarantine flag" ;;
  esac
  note "Dry run: nothing was downloaded or installed."
  exit 0
fi

# ---- Download and check -----------------------------------------------------
step "Downloading $label ($size_mb MB)"
curl -fL --progress-bar -o "$tmp/$name" "$url" || die "Download failed: $url"

if command -v sha256sum >/dev/null 2>&1; then
  actual=$(sha256sum "$tmp/$name" | cut -d ' ' -f 1)
elif command -v shasum >/dev/null 2>&1; then
  actual=$(shasum -a 256 "$tmp/$name" | cut -d ' ' -f 1)
else
  die "Neither sha256sum nor shasum is available to check the download."
fi
[ "$actual" = "$sha" ] || die "SHA-256 mismatch for $name (expected $sha, got $actual). Nothing was installed."
good "SHA-256 matches latest.json"

# ---- Install ----------------------------------------------------------------
case $kind in
  pacman)
    step "Installing with pacman; sudo asks for your password"
    as_root pacman -U --noconfirm "$tmp/$name"
    ;;
  deb)
    step "Installing with apt; sudo asks for your password"
    as_root apt-get install -y "$tmp/$name"
    ;;
  rpm)
    step "Installing with $PKG_TOOL; sudo asks for your password"
    if [ "$PKG_TOOL" = zypper ]; then
      as_root zypper --non-interactive install --allow-unsigned-rpm "$tmp/$name"
    else
      as_root dnf install -y "$tmp/$name"
    fi
    ;;
  appimage)
    step "Installing the AppImage to $pkg_name"
    mkdir -p "$BIN_DIR"
    chmod 755 "$tmp/$name"
    mv -f "$tmp/$name" "$pkg_name"
    ;;
  app)
    mkdir "$tmp/app"
    tar -xzf "$tmp/$name" -C "$tmp/app"
    [ -d "$tmp/app/Emisteme.app" ] || die "The archive $name has no Emisteme.app."
    step "Moving Emisteme.app to $APPLICATIONS_DIR"
    if [ -w "$APPLICATIONS_DIR" ]; then
      rm -rf "$pkg_name"
      mv "$tmp/app/Emisteme.app" "$pkg_name"
    else
      PKG_TOOL='mv'
      note "$APPLICATIONS_DIR is not writable by you; sudo asks for your password"
      as_root rm -rf "$pkg_name"
      as_root mv "$tmp/app/Emisteme.app" "$pkg_name"
    fi
    step "Removing the quarantine flag: the preview is not notarized yet, so macOS would refuse to open it"
    xattr -dr com.apple.quarantine "$pkg_name" 2>/dev/null || true
    ;;
esac

mkdir -p "$(dirname "$STATE_FILE")"
{
  printf 'version=%s\n' "$version"
  printf 'kind=%s\n' "$kind"
  printf 'tool=%s\n' "$PKG_TOOL"
  printf 'target=%s\n' "$pkg_name"
} >"$STATE_FILE"

printf '\n%s✓Emisteme %s is installed.%s\n' "$GREEN$BOLD" "$version" "$RESET"
case $kind in
  app) note "Open it from Launchpad, or run: open -a Emisteme" ;;
  appimage)
    note "Run: $pkg_name"
    case ":$PATH:" in
      *":$BIN_DIR:"*) ;;
      *) note "$BIN_DIR is not in your PATH; add it to run: emisteme" ;;
    esac
    ;;
  *) note "Open it from your applications, or run: emisteme" ;;
esac
note "Updates install themselves from now on."
