#!/usr/bin/env bash
set -euo pipefail

info(){ printf '[YuraBrowserApp] %s\n' "$*"; }
warn(){ printf '[YuraBrowserApp] %s\n' "$*" >&2; }
need(){ command -v "$1" >/dev/null 2>&1; }

DL="$HOME/Downloads"
mkdir -p "$DL"
PKG="$DL/yura-browser-app.tar.gz"
OUT="$DL/yura-browser-app"

ensure_node(){
  if need node && need npm; then return; fi
  warn "Node.js not found. Installing..."
  if need apt-get; then
    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - >/dev/null
    sudo apt-get install -y nodejs >/dev/null
  elif need brew; then
    brew install node >/dev/null
  else
    echo "Install Node.js manually, then re-run."; exit 1
  fi
}

info "Downloading latest Yura Browser App package..."
curl -fsSLo "$PKG" https://yuranetwork.com/downloads/yura-browser-app.tar.gz

rm -rf "$OUT"
mkdir -p "$OUT"
tar -xzf "$PKG" -C "$OUT"

ensure_node

cd "$OUT/yura-browser-app"
info "Installing dependencies..."
npm install
info "Starting app..."
npm start
