#!/bin/sh
# Waylo one-line installer — served at https://waylo.site/install.sh
#
#   wget -qO- https://waylo.site/install.sh | sh
#   # or, to inspect first:
#   wget -O install.sh https://waylo.site/install.sh && sh install.sh
#
# Runs as your normal desktop user (NOT root): Waylo installs a systemd *user*
# service that must live in your graphical session, and uses sudo only for
# system packages. Pass installer options after the script, e.g.:
#   wget -qO- https://waylo.site/install.sh | sh -s -- --port 9000 --no-https
set -e

BASE="https://waylo.site"
VERSION="0.4.16"
# SHA256 of waylo-${VERSION}-linux-x64.run (kept in lockstep with the upload).
CHECKSUM_x64="8b5a8e5bb5ff9fb897fb551c9af0632a62c9602ab8798fccf86fa49ac96d2bdf"

if [ "$(id -u)" -eq 0 ]; then
    echo "Waylo installs a per-user service, so run this as your normal desktop"
    echo "user rather than root:"
    echo "  wget -qO- ${BASE}/install.sh | sh"
    exit 1
fi

case "$(uname -m)" in
    x86_64|amd64)  ARCH=x64 ;;
    aarch64|arm64) ARCH=arm64 ;;
    *) echo "Unsupported architecture: $(uname -m). Waylo currently ships x86_64 builds."; exit 1 ;;
esac

RUN="waylo-${VERSION}-linux-${ARCH}.run"
URL="${BASE}/${RUN}"
TMP="$(mktemp -d)"
FILE="${TMP}/${RUN}"
trap 'rm -rf "$TMP"' EXIT

echo "Downloading Waylo ${VERSION} (${ARCH})..."
if command -v curl >/dev/null 2>&1; then
    curl -fSL "$URL" -o "$FILE" || { echo "Download failed: $URL"; exit 1; }
elif command -v wget >/dev/null 2>&1; then
    wget -O "$FILE" "$URL" || { echo "Download failed: $URL"; exit 1; }
else
    echo "Need curl or wget to download the installer."; exit 1
fi

[ -s "$FILE" ] || { echo "Downloaded installer is empty."; exit 1; }

# Verify the checksum for the arch we ship a known hash for.
eval "EXPECTED=\${CHECKSUM_${ARCH}:-}"
if [ -n "$EXPECTED" ]; then
    if command -v sha256sum >/dev/null 2>&1; then
        ACTUAL="$(sha256sum "$FILE" | awk '{print $1}')"
        if [ "$ACTUAL" != "$EXPECTED" ]; then
            echo "SHA256 checksum mismatch — aborting."
            echo "  expected $EXPECTED"
            echo "  got      $ACTUAL"
            exit 1
        fi
    else
        echo "Warning: sha256sum not found; skipping checksum verification."
    fi
fi

chmod +x "$FILE"
echo "Running the Waylo installer..."
# --nox11: this is a CLI installer; never let makeself relaunch the .run in an
# xterm. Attach the real terminal (/dev/tty) so the installer's prompts and the
# sudo password for system packages work even though this script arrived over a
# pipe (wget|sh). With no usable terminal (piped, no PTY), fall back to a
# non-interactive install. /dev/tty may *exist* yet not be openable when there's
# no controlling terminal — and in a non-interactive shell a failed redirect is
# fatal, so we probe it inside a subshell ( ) where the failure only exits the
# child, not this script.
if ( : < /dev/tty ) 2>/dev/null; then
    "$FILE" --nox11 -- "$@" < /dev/tty
else
    "$FILE" --nox11 -- -y "$@" < /dev/null
fi
