#!/bin/sh
# atlas-install.sh — the plain installer for the public Atlas Twilight Linux package (slice 049). No Python.
# It has one job a brand-new account needs: it makes the
# standard folders (~/.local, ~/.local/share, ~/.local/bin) itself, private to the user, instead of refusing.
#
#   atlas-install.sh install PACKAGE.tar TAR_SHA256 BINARY_SHA256   install, or install over the current one
#   atlas-install.sh launch [args]                                  start Atlas (the launcher runs this)
#   atlas-install.sh rollback                                       put the previous install back
#   atlas-install.sh verify                                         check installed bytes against the receipt
#
# The two hashes are published next to the download. Safety: pinned package and binary
# hashes; no links, devices, setuid/setgid or group/world-writable files in the payload; never install or roll back
# while Atlas runs; one lock for every action; the previous install is archived, never deleted; installed bytes are
# checked against the receipt at every launch. Your profile (settings, conversations) is never moved or rewritten.
set -eu
umask 077
NAME=titan-atlas-twilight
[ -n "${HOME:-}" ] && [ "${HOME#/}" != "$HOME" ] || { echo "REFUSED: UNSAFE_HOME" >&2; exit 2; }
[ "$(cd "$HOME" && pwd -P)" = "$HOME" ] || { echo "REFUSED: SYMLINK_HOME" >&2; exit 2; }
SHARE=$HOME/.local/share
ROOT=$SHARE/$NAME
PROFILE=$SHARE/$NAME-profile
LAUNCHER=$HOME/.local/bin/$NAME
LOCK=$SHARE/.$NAME.lock
# The one state folder a launch gives Atlas (launch exports it as XDG_STATE_HOME). The STOP fallback marker
# lives under it, so every STOP check below starts here. Keep this the only place the path is written.
STOP_STATE_HOME=$PROFILE/state
ACCOUNT_STOP_STATE_HOME=$HOME/.local/state
RECEIPT=$ROOT/.install-receipt.txt
BIN=$ROOT/usr/bin/titan-atlas-twilight

refuse() { echo "REFUSED: $*" >&2; exit 1; }
# A STOP the profile could not take is recorded in fallback markers that only builds from slice 029 on can read.
# Putting an older build in place while one exists would start Atlas running. Refuse instead: the owner starts Atlas
# again first (which removes the marker), or installs a build that reads it.
stop_state_dirs() {   # every folder this Atlas may have put a fallback STOP marker in, the launch one first
  printf '%s\n' "$STOP_STATE_HOME/titan-atlas" "$ACCOUNT_STOP_STATE_HOME/titan-atlas"
  case "${XDG_STATE_HOME:-}" in /*) printf '%s\n' "$XDG_STATE_HOME/titan-atlas" ;; esac
  case "${XDG_RUNTIME_DIR:-}" in /*) printf '%s\n' "$XDG_RUNTIME_DIR/titan-atlas" ;; esac
}
stop_marker_in_dir() {
  for marker in "$1"/desk-stop-*.json; do
    if [ -e "$marker" ] || [ -L "$marker" ]; then return 0; fi
  done
  return 1
}
fallback_stop() {   # is a fallback STOP marker present for this account? One folder per line, spaces kept.
  stop_state_dirs | {
    while IFS= read -r d; do
      if stop_marker_in_dir "$d"; then exit 0; fi
    done
    exit 1
  }
}
reads_fallback() {
  if stop_marker_in_dir "$ACCOUNT_STOP_STATE_HOME/titan-atlas"; then
    # Builds before account-state support can read the profile and runtime markers, but can miss this one.
    grep -q -a ATLAS_DESK_STOP_ACCOUNT_FALLBACK_V1 "$1" 2>/dev/null
  else
    grep -q -a ATLAS_DESK_STOP_FALLBACK_V1 "$1" 2>/dev/null
  fi
}
stamp() { date -u +%Y%m%dT%H%M%SZ; }
running() {   # is any process running this exact executable?
  target=$(readlink -f "$1" 2>/dev/null) || return 1
  for p in /proc/[0-9]*; do [ "$(readlink "$p/exe" 2>/dev/null)" = "$target" ] && return 0; done; return 1
}
standard_dirs() {   # a brand-new account may have none of these; make the missing ones, private to this user
  for d in "$HOME/.local" "$SHARE" "$HOME/.local/bin"; do
    if [ ! -e "$d" ] && [ ! -L "$d" ]; then mkdir -m 700 "$d" || refuse "CANNOT_CREATE: $d"; fi
    [ -d "$d" ] && [ ! -L "$d" ] && [ "$(stat -c %u "$d")" = "$(id -u)" ] || refuse "UNSAFE_DIRECTORY: $d"
  done
}
private_dir() { [ -d "$1" ] && [ ! -L "$1" ] && [ "$(stat -c %u "$1")" = "$(id -u)" ] && [ $(( 0$(stat -c %a "$1") & 022 )) -eq 0 ]; }
check_payload() {   # every entry: plain file or directory, owned by us after extract, no s-bits, not group/world writable
  bad=$(find "$1" \( -type l -o \( ! -type f ! -type d \) -o -perm /6022 -o -name '*.py' -o -name '*.pyc' \) -print | head -5)
  [ -z "$bad" ] || refuse "UNSAFE_PAYLOAD: $bad"
}
write_receipt() {   # sha256 of every installed file, relative to ROOT
  ( cd "$ROOT" && find usr -type f -print0 | sort -z | xargs -0 sha256sum ) > "$RECEIPT.tmp"
  { echo "# $NAME receipt · installed $(stamp) · package $1 · binary $2 · profile $PROFILE (not touched)"; cat "$RECEIPT.tmp"; } > "$RECEIPT"
  rm -f "$RECEIPT.tmp"; chmod 600 "$RECEIPT"
}
verify() {
  [ -f "$RECEIPT" ] && [ ! -L "$RECEIPT" ] || refuse "RECEIPT_MISSING"
  ( cd "$ROOT" && grep -v '^#' "$RECEIPT" | sha256sum --quiet --strict -c - ) || refuse "INSTALLED_BYTES_DRIFT"
  n_rec=$(grep -vc '^#' "$RECEIPT"); n_now=$(cd "$ROOT" && find usr -type f | wc -l)
  [ "$n_rec" = "$n_now" ] || refuse "INSTALLED_INVENTORY_DRIFT ($n_now files, receipt $n_rec)"
}
write_launcher() {
  tmp=$(mktemp "$HOME/.local/bin/.$NAME.XXXXXX")
  cat > "$tmp" <<EOF
#!/bin/sh
exec /bin/sh "$ROOT/.atlas-install.sh" launch "\$@"
EOF
  chmod 700 "$tmp"; mv -fT "$tmp" "$LAUNCHER"
}
with_lock() {   # run the rest under one exclusive lock (shared for launch)
  [ ! -L "$LOCK" ] || refuse "LOCK_REDIRECTED"
  exec 9>>"$LOCK"; chmod 600 "$LOCK"
  flock "$1" -n 9 || refuse "ATLAS_OR_INSTALLER_BUSY"
}

cmd=${1:-}; [ $# -gt 0 ] && shift
case "$cmd" in
install|upgrade)
  [ $# -eq 3 ] || refuse "USAGE: install PACKAGE.tar TAR_SHA256 BINARY_SHA256"
  pkg=$1; want_tar=$2; want_bin=$3
  [ -f "$pkg" ] && [ ! -L "$pkg" ] || refuse "PACKAGE_MISSING"
  [ "$(sha256sum "$pkg" | cut -d' ' -f1)" = "$want_tar" ] || refuse "PACKAGE_HASH_MISMATCH"
  standard_dirs
  private_dir "$SHARE" || refuse "UNSAFE_DIRECTORY: $SHARE (it is writable by other users)"
  with_lock -x
  running "$BIN" && refuse "CLOSE_ATLAS_FIRST"
  stage=$(mktemp -d "$SHARE/.$NAME-stage-XXXXXX")
  tar -x --no-same-owner --no-same-permissions --delay-directory-restore -f "$pkg" -C "$stage" usr \
    || { mv -T "$stage" "$stage.failed"; refuse "PACKAGE_EXTRACT_FAILED"; }
  check_payload "$stage"
  chmod -R go-w "$stage"
  [ "$(sha256sum "$stage/usr/bin/titan-atlas-twilight" | cut -d' ' -f1)" = "$want_bin" ] || { mv -T "$stage" "$stage.failed"; refuse "BINARY_HASH_MISMATCH"; }
  [ -d "$stage/usr/lib/Titan.Atlas Twilight Edition/modules" ] || { mv -T "$stage" "$stage.failed"; refuse "PACKAGE_LAYOUT (no usr/lib/<product>/modules)"; }
  if fallback_stop && ! reads_fallback "$stage/usr/bin/titan-atlas-twilight"; then
    mv -T "$stage" "$stage.failed"; refuse "STOP_WOULD_BE_LOST (Atlas is stopped by a STOP this build cannot see; start Atlas again first)"; fi
  cp "$0" "$stage/.atlas-install.sh"; chmod 700 "$stage/.atlas-install.sh"
  archive=""
  if [ -e "$ROOT" ]; then archive=$SHARE/.$NAME-previous-$(stamp); mv -T --no-clobber "$ROOT" "$archive"; [ -e "$archive" ] || refuse "ARCHIVE_FAILED"
    [ -e "$LAUNCHER" ] && cp -p "$LAUNCHER" "$archive/.launcher.previous"; fi
  if ! mv -T --no-clobber "$stage" "$ROOT" || [ ! -x "$BIN" ]; then
    [ -n "$archive" ] && [ -e "$archive" ] && [ ! -e "$ROOT" ] && mv -T "$archive" "$ROOT"; refuse "INSTALL_RENAME_FAILED (previous restored)"
  fi
  write_receipt "$want_tar" "$want_bin"; verify
  [ -n "$archive" ] && echo "$archive" > "$ROOT/.previous"
  write_launcher
  echo "INSTALLED $ROOT · binary $want_bin · previous ${archive:-none} · profile $PROFILE kept" ;;
launch)
  with_lock -s
  verify
  for d in "$PROFILE" "$PROFILE/data" "$PROFILE/config" "$STOP_STATE_HOME" "$PROFILE/cache"; do
    [ -e "$d" ] || mkdir -m 700 "$d"; private_dir "$d" || refuse "UNSAFE_PROFILE_DIRECTORY: $d"
  done
  unset ATLAS_ACCEPT_CONFIRM ATLAS_NATIVE_ACCEPTANCE WEBKIT_INSPECTOR_SERVER WEBKIT_INSPECTOR_HTTP_SERVER
  export XDG_DATA_HOME=$PROFILE/data XDG_CONFIG_HOME=$PROFILE/config XDG_STATE_HOME=$STOP_STATE_HOME XDG_CACHE_HOME=$PROFILE/cache
  exec "$BIN" "$@" ;;   # fd 9 keeps the shared lock for Atlas's whole life
rollback)
  with_lock -x
  running "$BIN" && refuse "CLOSE_ATLAS_FIRST"
  [ -f "$ROOT/.previous" ] || refuse "NO_PREVIOUS_INSTALL"
  prev=$(cat "$ROOT/.previous"); case "$prev" in "$SHARE/.$NAME-previous-"*) ;; *) refuse "PREVIOUS_SCOPE";; esac
  [ -d "$prev" ] && [ ! -L "$prev" ] || refuse "PREVIOUS_MISSING"
  if fallback_stop && ! reads_fallback "$prev/usr/bin/titan-atlas-twilight"; then
    refuse "STOP_WOULD_BE_LOST (Atlas is stopped by a STOP the previous build cannot see; start Atlas again first)"; fi
  out=$SHARE/.$NAME-rolledback-$(stamp)
  mv -T --no-clobber "$ROOT" "$out"; mv -T --no-clobber "$prev" "$ROOT"
  [ -f "$ROOT/.launcher.previous" ] && cp -p "$ROOT/.launcher.previous" "$LAUNCHER"
  echo "ROLLED BACK: $ROOT is the previous install again; the replaced one is $out; profile $PROFILE kept" ;;
verify) verify; echo "VERIFIED $ROOT against $RECEIPT" ;;
stop-dirs) stop_state_dirs ;;   # read-only: where this installer looks for a fallback STOP (used by the path check)
stop-present) if fallback_stop; then echo PRESENT; else echo ABSENT; fi ;;   # read-only: does it see one?
*) refuse "USAGE: install PACKAGE.tar TAR_SHA256 BINARY_SHA256 | launch | rollback | verify" ;;
esac
