#!/usr/bin/env bash
# Install (or update) the Wave Bot on an Ubuntu server.
# Run as root from the unzipped folder:   bash deploy/install-server.sh
# Safe to run again for updates: your .env, wallet connection, history and login sessions are kept.
set -euo pipefail
SRC="$(cd "$(dirname "$0")/.." && pwd)"
DEST=/home/botuser/wave-bot

echo "1/5 System packages"
apt-get update -qq
apt-get install -y -qq python3 python3-venv rsync >/dev/null

echo "2/5 Bot user"
id botuser &>/dev/null || adduser --disabled-password --gecos "" botuser >/dev/null

echo "3/5 Copying files (keeping your settings and data)"
mkdir -p "$DEST"
systemctl stop wave-bot 2>/dev/null || true
# keep a copy of all bot data (history, hooks, wallet connections) before updating
if [ -d "$DEST/data" ]; then
  BK="/root/wave-bot-backup-$(date +%Y%m%d-%H%M%S)"
  cp -a "$DEST/data" "$BK" && chmod 700 "$BK" && echo "    backup of your data: $BK"
fi
rsync -a --delete --exclude ".env" --exclude "data/" --exclude ".venv/" "$SRC"/ "$DEST"/
mkdir -p "$DEST/data"
[ -f "$DEST/.env" ] || cp "$DEST/.env.example" "$DEST/.env"
# on the server the page is only reachable through a secure connection, never directly from the internet
sed -i 's/^HOST=.*/HOST=127.0.0.1/' "$DEST/.env"

echo "4/5 Python libraries"
[ -d "$DEST/.venv" ] || python3 -m venv "$DEST/.venv"
"$DEST/.venv/bin/pip" install -q --upgrade pip
"$DEST/.venv/bin/pip" install -q -r "$DEST/requirements.txt"
chown -R botuser:botuser "$DEST"
chmod 600 "$DEST/.env"

echo "5/5 Background service"
cp "$DEST/deploy/wave-bot.service" /etc/systemd/system/wave-bot.service
systemctl daemon-reload
systemctl enable --now wave-bot >/dev/null
sleep 4
if systemctl is-active --quiet wave-bot; then
  echo
  echo "Wave Bot is running. It starts automatically after a reboot and restarts if it crashes."
  echo "Logs:  journalctl -u wave-bot -f"
else
  echo "The bot did not start. Show the error with:  journalctl -u wave-bot -n 40 --no-pager"
  exit 1
fi
