#!/bin/bash
# Installs SAC on THIS computer, so it can open apps, a terminal, files and more.
# (The normal install is only a window onto the website, which cannot do that.)
#   bash install-sac-local.sh              install or update
#   bash install-sac-local.sh --uninstall  remove it again
set -eu
URL="https://taskmanagerapi.nx-dev.cc"
UNINSTALL="0"
DIR="$HOME/.local/share/sac"
PORT=8765

if [ "${1:-}" = "--uninstall" ] || [ "$UNINSTALL" = 1 ]; then
    [ -x "$HOME/.local/bin/sac-local" ] && "$HOME/.local/bin/sac-local" --stop 2>/dev/null || true
    rm -f "$HOME/.local/bin/sac-local" "$HOME/.local/share/applications/sac-local.desktop" \
          "$HOME/.local/share/icons/sac-local.png"
    rm -rf "$HOME/.config/sac-local" "$DIR"
    update-desktop-database "$HOME/.local/share/applications" 2>/dev/null || true
    echo "SAC (this computer) removed, including its saved account, memories and key."
    exit 0
fi

[ "$(uname -s)" = Linux ] || { echo "Full-access SAC is Linux only for now."; exit 1; }
for c in curl tar python3; do
    command -v "$c" >/dev/null 2>&1 || { echo "$c is needed to install SAC."; exit 1; }
done
python3 -c 'import sys; sys.exit(sys.version_info < (3, 9))' \
    || { echo "SAC needs Python 3.9 or newer."; exit 1; }
BROWSER_BIN=""
for b in google-chrome google-chrome-stable chromium chromium-browser microsoft-edge brave-browser; do
    command -v "$b" >/dev/null 2>&1 && { BROWSER_BIN="$b"; break; }
done
[ -n "$BROWSER_BIN" ] || { echo "SAC needs Chrome, Chromium, Edge or Brave for its window."; exit 1; }

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
echo "Downloading SAC ..."
curl -fsSL "$URL/install/sac-local.tar.gz" -o "$TMP/sac.tar.gz" || { echo "Could not reach $URL"; exit 1; }
mkdir -p "$TMP/new" "$DIR"
tar -xzf "$TMP/sac.tar.gz" -C "$TMP/new"
# Code is always replaced. The lessons file is yours once SAC has learned in it,
# so it is only written the first time. Accounts, memories and the key stay put.
for f in "$TMP/new/"*; do
    base="$(basename "$f")"
    if [ "$base" = mini_gpt_chats.txt ] && [ -e "$DIR/$base" ]; then continue; fi
    rm -rf "$DIR/$base"; cp -r "$f" "$DIR/$base"
done

echo "Setting up Python (a minute the first time) ..."
if [ ! -x "$DIR/venv/bin/python3" ]; then
    python3 -m venv "$DIR/venv" || { echo "Could not make a Python environment. On Ubuntu/Debian run: sudo apt install python3-venv"; exit 1; }
fi
"$DIR/venv/bin/pip" install --quiet --disable-pip-version-check openai requests pathvalidate numpy gTTS \
    || { echo "Could not install SAC's Python packages."; exit 1; }

# SAC thinks through Groq, which gives free keys. Each person uses their own.
if ! grep -qs '^GROQ_API_KEY=.' "$DIR/.env"; then
    echo
    echo "SAC needs a free Groq API key: open https://console.groq.com/keys , create one, and paste it here."
    KEY=""
    if [ -r /dev/tty ]; then
        printf "Groq API key: " > /dev/tty
        IFS= read -r KEY < /dev/tty || true
    fi
    KEY="$(printf '%s' "$KEY" | tr -d '[:space:]')"
    if [ -z "$KEY" ]; then
        echo "No key entered. Add this line to $DIR/.env , then open SAC:"
        echo "    GROQ_API_KEY=gsk_..."
    else
        case "$KEY" in gsk_*) ;; *) echo "(that does not look like a Groq key, saving it anyway)" ;; esac
        ( umask 077; printf 'GROQ_API_KEY=%s\n' "$KEY" > "$DIR/.env" )
    fi
fi
[ -e "$DIR/.env" ] && chmod 600 "$DIR/.env"

mkdir -p "$HOME/.local/bin" "$HOME/.local/share/applications" "$HOME/.local/share/icons"
cp "$DIR/media/sac-icon.png" "$HOME/.local/share/icons/sac-local.png"

# Only this computer may talk to it (127.0.0.1): it can open apps and files, so
# nobody else on the network must ever be able to reach it.
cat > "$HOME/.local/bin/sac-local" <<LAUNCH
#!/bin/bash
DIR="$DIR"
PORT=$PORT
BROWSER_BIN="$BROWSER_BIN"
LOCALURL="http://127.0.0.1:\$PORT"
PIDFILE="\$DIR/.sac.pid"
say() { notify-send "SAC" "\$1" 2>/dev/null || echo "\$1"; }
up() { curl -sf -o /dev/null --max-time 2 "\$LOCALURL"; }
if [ "\${1:-}" = "--stop" ]; then
    kill "\$(cat "\$PIDFILE" 2>/dev/null)" 2>/dev/null && say "SAC stopped" || true
    exit 0
fi
grep -qs '^GROQ_API_KEY=.' "\$DIR/.env" || { say "SAC has no API key. Add GROQ_API_KEY=... to \$DIR/.env"; exit 1; }
STARTED=0
if ! up; then
    set -a; . "\$DIR/.env"; set +a
    cd "\$DIR"
    SAC_NO_BROWSER=1 SAC_WEB_HOST=127.0.0.1 SAC_WEB_PORT="\$PORT" PYTHONUTF8=1 \\
        nohup "\$DIR/venv/bin/python3" "\$DIR/sac_web.py" >"\$DIR/sac.log" 2>&1 &
    echo \$! > "\$PIDFILE"; STARTED=1
    for _ in \$(seq 1 40); do up && break; sleep 0.5; done
fi
up || { say "SAC could not start. See \$DIR/sac.log"; exit 1; }
"\$BROWSER_BIN" --app="\$LOCALURL" --class=SAC-local --user-data-dir="\$HOME/.config/sac-local" >/dev/null 2>&1
# The window was closed: stop the server we started, so nothing keeps running.
[ "\$STARTED" = 1 ] && kill "\$(cat "\$PIDFILE" 2>/dev/null)" 2>/dev/null || true
LAUNCH
chmod +x "$HOME/.local/bin/sac-local"

cat > "$HOME/.local/share/applications/sac-local.desktop" <<DESK
[Desktop Entry]
Type=Application
Name=SAC (this computer)
Comment=Smart Assistant Cloud with access to this computer
Exec="$HOME/.local/bin/sac-local"
Icon=$HOME/.local/share/icons/sac-local.png
Terminal=false
Categories=Network;
StartupNotify=true
StartupWMClass=SAC-local
DESK
update-desktop-database "$HOME/.local/share/applications" 2>/dev/null || true
echo
echo "Done. Open 'SAC (this computer)' from your applications menu, or run: $HOME/.local/bin/sac-local"
echo "First time: create an account on the sign-in page. It is stored only on this computer."
