#!/bin/sh
# Deck OS: builds (or checks) Deck OS's own private copy of its Python parts in /opt/deckos/venv,
# from /opt/deckos/app/requirements.txt. The package runs this once when it's installed or updated,
# and the service runs it before starting (it's instant when everything is already in place).
#   sudo /opt/deckos/bin/deckos-setup          set it up (again)
#   deckos-setup --check                       just say whether it's ready (no changes)
#   deckos-setup --if-needed                   set it up only if it isn't ready
set -eu
APP=/opt/deckos/app
VENV=/opt/deckos/venv
REQ="$APP/requirements.txt"
STAMP="$VENV/.deckos-requirements.sha256"
want=$(sha256sum "$REQ" | cut -d' ' -f1)

ready() {
  [ -x "$VENV/bin/python" ] && [ "$(cat "$STAMP" 2>/dev/null)" = "$want" ] &&
    "$VENV/bin/python" -c 'import fastapi, uvicorn, httpx, cryptography, PIL, psutil, segno' 2>/dev/null
}

case "${1:-}" in
  --check) ready && exit 0
           echo "Deck OS isn't finished installing. Run this, then try again:   sudo /opt/deckos/bin/deckos-setup" >&2
           exit 1 ;;
  --if-needed) ready && exit 0 ;;
  "") ;;
  *) echo "Unknown option: $1" >&2; exit 2 ;;
esac

if [ "$(id -u)" != 0 ]; then
  echo "This needs your password. Run:   sudo /opt/deckos/bin/deckos-setup" >&2
  exit 1
fi
command -v python3 >/dev/null || { echo "Deck OS needs Python 3. Ubuntu/Debian/Mint: sudo apt install python3 python3-venv   Fedora: sudo dnf install python3" >&2; exit 1; }
python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)' ||
  { echo "Deck OS needs Python 3.10 or newer (this computer has $(python3 -V 2>&1))." >&2; exit 1; }

echo "Deck OS: setting up its Python parts (a one-time download of about 40 MB; takes a minute or two)..."
NEW="$VENV.new"
rm -rf "$NEW"
if ! python3 -m venv "$NEW" >/dev/null 2>&1; then
  rm -rf "$NEW"
  echo "Python's venv module is missing. Ubuntu/Debian/Mint: sudo apt install python3-venv   then: sudo /opt/deckos/bin/deckos-setup" >&2
  exit 1
fi
if ! "$NEW/bin/python" -m pip install --quiet --disable-pip-version-check --no-cache-dir -r "$REQ"; then
  rm -rf "$NEW"
  echo "Couldn't download Deck OS's Python parts. Check the internet connection, then run:   sudo /opt/deckos/bin/deckos-setup" >&2
  exit 1
fi
echo "$want" > "$NEW/.deckos-requirements.sha256"
chmod -R u=rwX,go=rX "$NEW"
rm -rf "$VENV"
mv "$NEW" "$VENV"
echo "Deck OS: Python parts ready."
