#!/usr/bin/env bash
# sws CLI installer: curl -fsSL https://sws.segura.my/install | bash
# Downloads the binary for this system, checks the SHA256 and installs to ~/.local/bin/sws.
# The old client (Python, .pyz) is kept as ~/.local/bin/sws-legacy.
set -euo pipefail
BASE=https://sws.segura.my/dl
os=$(uname -s | tr A-Z a-z); arch=$(uname -m)
case "$arch" in x86_64|amd64) arch=amd64;; arm64|aarch64) arch=arm64;; *) echo "unsupported architecture: $arch" >&2; exit 1;; esac
case "$os" in darwin|linux) ;; *) echo "unsupported OS: $os" >&2; exit 1;; esac
BIN="$HOME/.local/bin/sws"; mkdir -p "$HOME/.local/bin"
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
curl -fsSL "$BASE/sws-$os-$arch" -o "$tmp/sws"
curl -fsSL "$BASE/SHA256SUMS" -o "$tmp/SHA256SUMS"
want=$(awk -v f="sws-$os-$arch" '$2==f{print $1}' "$tmp/SHA256SUMS")
got=$( (command -v sha256sum >/dev/null && sha256sum "$tmp/sws" || shasum -a 256 "$tmp/sws") | cut -d' ' -f1)
[ -n "$want" ] && [ "$want" = "$got" ] || { echo "SHA256 mismatch" >&2; exit 1; }
# The old client is a Python zipapp (starts with the shebang, has __main__.py).
if [ -f "$BIN" ] && grep -qa "__main__.py" "$BIN"; then mv -f "$BIN" "$HOME/.local/bin/sws-legacy"; echo "old client kept at ~/.local/bin/sws-legacy"; fi
install -m 0755 "$tmp/sws" "$BIN"
echo "✓ sws 6d3527c installed at $BIN"
case ":$PATH:" in
  *":$HOME/.local/bin:"*) ;;
  *) RC="$HOME/.bashrc"; case "${SHELL##*/}" in zsh) RC="$HOME/.zshrc";; esac
     LINE='export PATH="$HOME/.local/bin:$PATH"'
     grep -qsF "$LINE" "$RC" 2>/dev/null || printf '\n%s\n' "$LINE" >> "$RC"
     echo "✓ ~/.local/bin added to PATH in $RC (open a new terminal)";;
esac
echo "next step: sws auth login"
