#!/bin/sh
# Workshare server - install on Linux as a systemd service, with PostgreSQL for customer data, Caddy for HTTPS and
# a nightly backup.
# Works on Ubuntu / Debian (apt) and RHEL / Rocky / AlmaLinux / Fedora / Amazon Linux (dnf).
#
# Run from the WorkshareServer folder (the one with package.json):
#   Internet:     sudo sh deploy/linux/install-linux.sh --domain workshare.globalinfocloud.in --email it@yourcompany.com
#   Office only:  sudo sh deploy/linux/install-linux.sh --lan 192.168.1.50
#   Check only:   sudo sh deploy/linux/install-linux.sh --check        (changes nothing, reports what is missing)
#   No database:  add --files to keep everything in files like version 0.6 (not recommended for customers)
#   Your MySQL:   add --mysql-url-file /root/workshare-db-url   (a file with one line: mysql://workshare:PASSWORD@127.0.0.1:3306/workshare)
#                 Uses an existing MySQL 8 instead of installing PostgreSQL. Create the database and user first:
#                   CREATE DATABASE workshare CHARACTER SET utf8mb4 COLLATE utf8mb4_bin;
#                   CREATE USER 'workshare'@'localhost' IDENTIFIED BY '<long random password>';
#                   GRANT ALL PRIVILEGES ON workshare.* TO 'workshare'@'localhost';
#
# Safe to run again (for example after fixing something); it keeps existing models, the database and the create token.
# Running it on a server that used files before moves the existing models into the database (they are backed up first).
set -eu

DOMAIN=""; EMAIL=""; LAN=""; CHECK=0; FILES=0; MYSQL_URL_FILE=""
while [ $# -gt 0 ]; do
  case "$1" in
    --domain) DOMAIN="${2:-}"; shift 2 ;;
    --email) EMAIL="${2:-}"; shift 2 ;;
    --lan) LAN="${2:-}"; shift 2 ;;
    --check) CHECK=1; shift ;;
    --files) FILES=1; shift ;;
    --mysql-url-file) MYSQL_URL_FILE="${2:-}"; shift 2 ;;
    *) echo "unknown option $1"; exit 1 ;;
  esac
done

ok()   { printf '  \033[32mOK\033[0m    %s\n' "$1"; }
warn() { printf '  \033[33mWARN\033[0m  %s\n' "$1"; }
bad()  { printf '  \033[31mFAIL\033[0m  %s\n' "$1"; FAILS=$((FAILS+1)); }
step() { printf '\n== %s\n' "$1"; }
FAILS=0

# ------------------------------------------------------------------ checks (always run)
step "Checking this server"
[ "$(id -u)" = 0 ] && ok "running as root (sudo)" || bad "run with sudo"
[ -f package.json ] && [ -d src ] && ok "in the WorkshareServer folder" || bad "cd into the WorkshareServer folder first (it contains package.json)"
command -v systemctl >/dev/null 2>&1 && ok "systemd present" || bad "systemd not found (this script needs systemd)"

. /etc/os-release 2>/dev/null || true
OS="${PRETTY_NAME:-unknown Linux}"
if command -v apt-get >/dev/null 2>&1; then PKG=apt; elif command -v dnf >/dev/null 2>&1; then PKG=dnf; elif command -v yum >/dev/null 2>&1; then PKG=dnf; else PKG=none; fi
ok "OS: $OS (package manager: $PKG)"

NODE="$(command -v node 2>/dev/null || true)"
if [ -z "$NODE" ]; then
  bad "node not found for root. If it was installed with nvm for one user, the service cannot use it (see guide, 'Node.js installed with nvm')"
else
  NODE="$(readlink -f "$NODE")"
  MAJOR="$("$NODE" -p 'process.versions.node.split(".")[0]')"
  if [ "$MAJOR" -ge 20 ]; then ok "Node $("$NODE" --version) at $NODE"; else bad "Node $("$NODE" --version) is too old (need 20+)"; fi
  case "$NODE" in
    /home/*|/root/*) bad "Node is inside a home folder ($NODE), probably nvm. The 'workshare' service user cannot run it. Install Node system-wide (guide, 'Node.js installed with nvm')" ;;
  esac
fi

MEM_MB="$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || echo 0)"
[ "$MEM_MB" -ge 7000 ] && ok "RAM ${MEM_MB} MB" || warn "RAM ${MEM_MB} MB (8 GB recommended for customers: ~1 GB per worker thread)"
DISK_GB="$(df -Pk /var 2>/dev/null | awk 'NR==2 {print int($4/1048576)}')"
[ "${DISK_GB:-0}" -ge 20 ] && ok "free disk on /var: ${DISK_GB} GB" || warn "free disk on /var: ${DISK_GB:-?} GB (20 GB+ recommended)"

PORTS_USED=""
if command -v ss >/dev/null 2>&1; then
  for p in 80 443 8080; do
    who="$(ss -ltnpH "sport = :$p" 2>/dev/null | sed -n 's/.*users:(("\([^"]*\)".*/\1/p' | head -1)"
    if [ -n "$who" ]; then
      case "$who" in caddy|node) ok "port $p used by $who (from an earlier install, fine)" ;; *) bad "port $p is already used by '$who' - ask your manager (guide, 'Port already in use')"; PORTS_USED=1 ;; esac
    else ok "port $p free"; fi
  done
fi

if command -v getenforce >/dev/null 2>&1 && [ "$(getenforce 2>/dev/null)" = "Enforcing" ]; then SELINUX=1; ok "SELinux enforcing (the script allows Caddy to reach the app)"; else SELINUX=0; fi
FW=none
if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q "Status: active"; then FW=ufw; fi
if command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then FW=firewalld; fi
ok "firewall on this server: $FW"

if [ "$FILES" = 1 ]; then ok "storage: files (--files)"
elif [ -n "$MYSQL_URL_FILE" ]; then
  if [ -f "$MYSQL_URL_FILE" ] && grep -q '^mysql://' "$MYSQL_URL_FILE"; then ok "storage: your MySQL (address in $MYSQL_URL_FILE)"
  else bad "$MYSQL_URL_FILE must exist and hold one line mysql://user:password@host:3306/database"; fi
  command -v npm >/dev/null 2>&1 && ok "npm found (installs the MySQL driver)" || bad "npm not found: it comes with Node.js; the MySQL driver is installed with it"
  command -v mysqldump >/dev/null 2>&1 && ok "mysqldump found (nightly backup)" || warn "mysqldump not found: install the MySQL client tools for the nightly database backup"
elif command -v psql >/dev/null 2>&1; then ok "PostgreSQL client found ($(psql --version | awk '{print $3}')); the database is set up by this script"
else ok "PostgreSQL not installed yet; this script installs it"; fi
command -v runuser >/dev/null 2>&1 || bad "runuser not found (part of util-linux)"

if [ "$CHECK" = 1 ]; then
  echo
  [ "$FAILS" = 0 ] && echo "Check passed. Run again with --domain/--email or --lan to install." || echo "$FAILS problem(s) above. Fix them, then run again."
  exit 0
fi

if [ -n "$LAN" ]; then SITE="$LAN"; MODE=lan
elif [ -n "$DOMAIN" ] && [ -n "$EMAIL" ]; then SITE="$DOMAIN"; MODE=internet
else echo; echo "Give --domain <name> --email <address> (internet) or --lan <server IP or name> (office only)."; exit 1; fi
[ "$FAILS" = 0 ] || { echo; echo "Fix the FAIL lines above first (nothing was changed)."; exit 1; }

# ------------------------------------------------------------------ install
step "User, folders, program files"
id workshare >/dev/null 2>&1 || useradd --system --home-dir /opt/workshare --shell /usr/sbin/nologin workshare 2>/dev/null || useradd --system --home-dir /opt/workshare --shell /sbin/nologin workshare
mkdir -p /opt/workshare /var/lib/workshare/models /var/backups/workshare /etc/workshare
rm -rf /opt/workshare/src
rm -rf /opt/workshare/tools
cp -r src tools package.json deploy /opt/workshare/
# The exact driver versions that were tested (MySQL only; npm install below reads it).
[ -f package-lock.json ] && cp package-lock.json /opt/workshare/
chown -R root:root /opt/workshare
chown -R workshare:workshare /var/lib/workshare
if [ ! -f /etc/workshare/workshare.env ]; then
  echo "WORKSHARE_CREATE_TOKEN=$(head -c 24 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\n')" > /etc/workshare/workshare.env
  chmod 600 /etc/workshare/workshare.env
  ok "create token generated in /etc/workshare/workshare.env"
else ok "keeping the existing /etc/workshare/workshare.env"; fi
# Secret for Kavion accounts (stored as an HMAC of the mobile number). Made once, never replaced: changing it would
# cut every customer off from their models. It is in the nightly backup together with the database.
if ! grep -q '^WORKSHARE_ACCOUNT_SECRET=' /etc/workshare/workshare.env; then
  echo "WORKSHARE_ACCOUNT_SECRET=$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\n')" >> /etc/workshare/workshare.env
  ok "account secret generated (needed when Kavion login is switched on; never change it)"
fi

DB_URL="postgres://workshare@/workshare"
if [ -n "$MYSQL_URL_FILE" ]; then
  step "MySQL (customer data, your existing server)"
  grep -q '^mysql://' "$MYSQL_URL_FILE" || { echo "$MYSQL_URL_FILE must hold one line mysql://user:password@host:3306/database"; exit 1; }
  # The address holds the password: root-owned, readable by the service group only.
  head -1 "$MYSQL_URL_FILE" | tr -d '\r\n' > /etc/workshare/database-url
  chown root:workshare /etc/workshare/database-url
  chmod 640 /etc/workshare/database-url
  (cd /opt/workshare && npm install --omit=dev --ignore-scripts --no-audit --no-fund --loglevel=error) || { bad "npm install failed (the server needs internet access to registry.npmjs.org once)"; exit 1; }
  ok "MySQL driver installed"
  if (cd / && runuser -u workshare -- env WORKSHARE_DATABASE_URL_FILE=/etc/workshare/database-url "$NODE" /opt/workshare/tools/db-setup.js); then ok "database checked, tables ready"
  else bad "the database check failed (see above). Fix the address or rights, then run this script again."; exit 1; fi
  if ! grep -q '^WORKSHARE_DATABASE_URL_FILE=' /etc/workshare/workshare.env; then
    if ls /var/lib/workshare/models/*/model.json >/dev/null 2>&1 && ! grep -q '^WORKSHARE_DATABASE_URL=' /etc/workshare/workshare.env; then
      systemctl stop workshare 2>/dev/null || true
      WORKSHARE_DATA_DIR=/var/lib/workshare/models BACKUP_DIR=/var/backups/workshare sh deploy/backup.sh
      if (cd / && runuser -u workshare -- env WORKSHARE_DATA_DIR=/var/lib/workshare/models WORKSHARE_DATABASE_URL_FILE=/etc/workshare/database-url "$NODE" /opt/workshare/tools/import-files-to-db.js); then
        ok "existing models moved into MySQL (model.json files kept as they were)"
      else bad "import failed; the server stays on files. See the lines above."; exit 1; fi
    fi
    sed -i '/^WORKSHARE_DATABASE_URL=/d' /etc/workshare/workshare.env
    echo "WORKSHARE_DATABASE_URL_FILE=/etc/workshare/database-url" >> /etc/workshare/workshare.env
    ok "server switched to MySQL"
  else ok "server already uses MySQL"; fi
  ok "you can delete $MYSQL_URL_FILE now (the address is kept in /etc/workshare/database-url)"
elif [ "$FILES" = 0 ]; then
  step "PostgreSQL (customer data)"
  if ! command -v pg_ctlcluster >/dev/null 2>&1 && ! command -v postgresql-setup >/dev/null 2>&1 && ! systemctl list-unit-files 'postgresql*' 2>/dev/null | grep -q postgresql; then
    if [ "$PKG" = apt ]; then apt-get update -y && apt-get install -y postgresql
    elif [ "$PKG" = dnf ]; then dnf install -y postgresql-server postgresql
    else echo "Install PostgreSQL by hand, then run this script again (or use --files)."; exit 1; fi
  fi
  if [ "$PKG" = dnf ] && command -v postgresql-setup >/dev/null 2>&1 && [ ! -f /var/lib/pgsql/data/PG_VERSION ]; then
    postgresql-setup --initdb >/dev/null
  fi
  systemctl enable postgresql >/dev/null 2>&1 || true
  systemctl start postgresql
  for i in 1 2 3 4 5 6 7 8 9 10; do (cd / && runuser -u postgres -- psql -tAc 'SELECT 1' >/dev/null 2>&1) && break; sleep 1; done
  pg() { (cd / && runuser -u postgres -- psql -v ON_ERROR_STOP=1 -tAc "$1"); }
  [ "$(pg "SELECT 1 FROM pg_roles WHERE rolname = 'workshare'")" = 1 ] || pg "CREATE ROLE workshare LOGIN" >/dev/null
  [ "$(pg "SELECT 1 FROM pg_database WHERE datname = 'workshare'")" = 1 ] || pg "CREATE DATABASE workshare OWNER workshare" >/dev/null
  # Only the local 'workshare' Linux user can log in as the 'workshare' database role (peer login over the local
  # socket): no password exists, and the database is not reachable from the network.
  if (cd / && runuser -u workshare -- psql -d workshare -tAc 'SELECT 1' >/dev/null 2>&1); then ok "database 'workshare' ready, login only for the workshare user on this machine"
  else bad "the workshare user cannot log in to PostgreSQL. Check that pg_hba.conf has: local all all peer"; exit 1; fi

  if ! grep -q '^WORKSHARE_DATABASE_URL=' /etc/workshare/workshare.env; then
    if ls /var/lib/workshare/models/*/model.json >/dev/null 2>&1; then
      systemctl stop workshare 2>/dev/null || true
      WORKSHARE_DATA_DIR=/var/lib/workshare/models BACKUP_DIR=/var/backups/workshare sh deploy/backup.sh
      if (cd / && runuser -u workshare -- env WORKSHARE_DATA_DIR=/var/lib/workshare/models WORKSHARE_DATABASE_URL="$DB_URL" "$NODE" /opt/workshare/tools/import-files-to-db.js); then
        ok "existing models moved into the database (model.json files kept as they were)"
      else bad "import failed; the server stays on files. See the lines above."; exit 1; fi
    fi
    echo "WORKSHARE_DATABASE_URL=$DB_URL" >> /etc/workshare/workshare.env
    ok "server switched to the database"
  else ok "server already uses the database"; fi
fi

step "Service 'workshare'"
sed "s#/usr/bin/node#$NODE#" deploy/workshare.service > /etc/systemd/system/workshare.service
systemctl daemon-reload
systemctl enable workshare >/dev/null 2>&1
systemctl restart workshare
ok "workshare service enabled and started"

step "Caddy (HTTPS)"
if ! command -v caddy >/dev/null 2>&1; then
  if [ "$PKG" = apt ]; then
    apt-get update -y
    apt-get install -y debian-keyring debian-archive-keyring apt-transport-https curl gpg
    curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
    curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' > /etc/apt/sources.list.d/caddy-stable.list
    apt-get update -y && apt-get install -y caddy
  elif [ "$PKG" = dnf ]; then
    dnf install -y 'dnf-command(copr)' && dnf copr enable -y @caddy/caddy && dnf install -y caddy
  else
    echo "Install Caddy by hand (https://caddyserver.com/docs/install), then run this script again."; exit 1
  fi
fi
ok "caddy $(caddy version 2>/dev/null | cut -d' ' -f1)"

if [ "$MODE" = internet ]; then
  GLOBAL="	email $EMAIL"
  TLS=""
else
  GLOBAL="	local_certs"
  TLS="	tls internal"
fi
[ -f /etc/caddy/Caddyfile ] && cp /etc/caddy/Caddyfile "/etc/caddy/Caddyfile.before-workshare.$(date +%s)"
cat > /etc/caddy/Caddyfile <<CADDY
{
$GLOBAL
}

$SITE {
$TLS
	request_body {
		max_size 48MB
	}
	header {
		Strict-Transport-Security "max-age=31536000"
		-Server
	}
	reverse_proxy 127.0.0.1:8080 {
		transport http {
			read_timeout 5m
			write_timeout 5m
		}
	}
}
CADDY
caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile >/dev/null
[ "$SELINUX" = 1 ] && setsebool -P httpd_can_network_connect 1 2>/dev/null || true
systemctl enable caddy >/dev/null 2>&1
systemctl restart caddy
ok "caddy serving https://$SITE"

step "Firewall: 80 and 443 in, 8080 stays closed"
case "$FW" in
  ufw) ufw allow OpenSSH >/dev/null; ufw allow 80/tcp >/dev/null; ufw allow 443/tcp >/dev/null; ok "ufw rules added" ;;
  firewalld) firewall-cmd --permanent --add-service=http >/dev/null; firewall-cmd --permanent --add-service=https >/dev/null; firewall-cmd --reload >/dev/null; ok "firewalld rules added" ;;
  *) warn "no firewall active on this server; make sure the cloud / company firewall allows 80 and 443 only" ;;
esac

step "Nightly backup (02:30)"
cat > /etc/cron.d/workshare-backup <<CRON
SHELL=/bin/sh
30 2 * * * root WORKSHARE_ENV_FILE=/etc/workshare/workshare.env WORKSHARE_DATA_DIR=/var/lib/workshare/models BACKUP_DIR=/var/backups/workshare KEEP_DAYS=14 sh /opt/workshare/deploy/backup.sh >> /var/log/workshare-backup.log 2>&1
CRON
chmod 644 /etc/cron.d/workshare-backup
ok "backups go to /var/backups/workshare (14 days kept; database + house files)"

step "Testing"
sleep 2
if curl -fsS http://127.0.0.1:8080/ready >/dev/null 2>&1; then ok "workshare answers on 127.0.0.1:8080"; else bad "workshare does not answer: journalctl -u workshare -n 50"; fi
if [ "$MODE" = lan ]; then
  curl -fsS --insecure "https://$SITE/health" >/dev/null 2>&1 && ok "https://$SITE answers" || warn "https://$SITE did not answer yet (check: journalctl -u caddy -n 50)"
else
  curl -fsS "https://$SITE/health" >/dev/null 2>&1 && ok "https://$SITE answers with a valid certificate" || warn "https://$SITE not ready yet. Certificates need DNS pointing here and port 80 open; Caddy retries by itself (journalctl -u caddy -f)"
fi

echo
echo "Done."
echo "  Unity server address : https://$SITE"
echo "  Create token         : sudo cat /etc/workshare/workshare.env"
echo "  Logs                 : journalctl -u workshare -f      (Caddy: journalctl -u caddy -f)"
if grep -q '^WORKSHARE_DATABASE_URL_FILE=' /etc/workshare/workshare.env; then
echo "  Customer data        : your MySQL (address in /etc/workshare/database-url)"
elif grep -q '^WORKSHARE_DATABASE_URL=' /etc/workshare/workshare.env; then
echo "  Customer data        : PostgreSQL database 'workshare'   (look inside: sudo -u workshare psql workshare)"
fi
echo "  House files          : /var/lib/workshare/models"
echo "  Backups              : /var/backups/workshare"
if [ "$MODE" = lan ]; then
  ROOT="$(find /var/lib/caddy /root/.local/share/caddy -path '*pki/authorities/local/root.crt' 2>/dev/null | head -1)"
  echo "  Root certificate     : ${ROOT:-/var/lib/caddy/.local/share/caddy/pki/authorities/local/root.crt}  (install on every Unity PC)"
fi
