#!/bin/bash
# ===========================================================================
#  SpinCraft ERP — one-shot deploy / repair script
#  Run this ON THE SERVER (SSH shell, or have the host run it as root).
#  It is safe to run more than once (idempotent).
#
#  What it does:
#    1. Kills the stuck node/npm processes that jammed the account (frees slots)
#    2. Points Prisma at the MySQL *socket* (the server has no TCP 3306)
#    3. Ensures dependencies + Prisma engine are present
#    4. Sets all 9 logins to password: admin123
#    5. Starts the app behind the Apache proxy on port 3100
#    6. Installs a keepalive cron and verifies an admin login
# ===========================================================================
set -u

APP=/home/erpsolution26/public_html/spincraft.erpsolution26.com
PORT=3100
DBU='erpsolution26_spincraft'
DBP='y61JTjJiBBNqnwRPJTCg6wJl'
DBN='erpsolution26_spincraft'
AUTHSECRET='LWq4tHjtKMiLs6IBjm3m0mKTkgypveVUmZL2jqD4VlGnkoDRMe_7jgMgyPQ3OVco'
ADMIN_HASH='$2a$10$3MgCkAocwuzVcxHjY6GSNOcihoCIDmcfDo.qWroTBaFRhKxxaHpt6'

echo "================ SpinCraft deploy  $(date) ================"

# --- 0. locate node (CloudLinux alt-nodejs) --------------------------------
NODEBIN=""
for v in 22 20 24 18; do
  [ -x /opt/alt/alt-nodejs$v/root/usr/bin/node ] && NODEBIN=/opt/alt/alt-nodejs$v/root/usr/bin && break
done
# fall back to whatever node is on PATH
[ -z "$NODEBIN" ] && command -v node >/dev/null 2>&1 && NODEBIN=$(dirname "$(command -v node)")
if [ -z "$NODEBIN" ]; then echo "FATAL: no node found"; exit 1; fi
export PATH="$NODEBIN:$PATH"
export HOME=/home/erpsolution26
export NODE_ENV=production
echo "[i] node $(node -v)  ($NODEBIN)"

# --- 1. break the process jam ----------------------------------------------
echo "[1] killing stray npm/next/prisma processes ..."
pkill -9 -u erpsolution26 -f 'npm install'   2>/dev/null
pkill -9 -u erpsolution26 -f 'npm exec'       2>/dev/null
pkill -9 -u erpsolution26 -f 'prisma'         2>/dev/null
pkill -9 -u erpsolution26 -f 'next start'     2>/dev/null
pkill -9 -u erpsolution26 -f 'next-server'    2>/dev/null
[ -f "$APP/node.pid" ] && kill -9 "$(cat "$APP/node.pid")" 2>/dev/null
sleep 2
echo "    processes now: $(ps -u erpsolution26 --no-headers 2>/dev/null | wc -l)"

cd "$APP" || { echo "FATAL: $APP missing"; exit 1; }

# --- 2. detect the MySQL socket + write .env -------------------------------
echo "[2] configuring database connection (socket) ..."
SOCK=$(mysql -u "$DBU" -p"$DBP" "$DBN" -N -e "SHOW VARIABLES LIKE 'socket';" 2>/dev/null | awk '{print $2}')
if [ -z "$SOCK" ] || [ ! -S "$SOCK" ]; then
  for c in /var/lib/mysql/mysql.sock /tmp/mysql.sock /var/run/mysqld/mysqld.sock; do
    [ -S "$c" ] && SOCK="$c" && break
  done
fi
echo "    socket: ${SOCK:-NOT FOUND}"
cat > .env <<ENVEOF
DATABASE_URL="mysql://$DBU:$DBP@localhost/$DBN?socket=$SOCK"
AUTH_SECRET="$AUTHSECRET"
NEXT_PUBLIC_APP_NAME="SpinCraft ERP"
NODE_ENV=production
PORT=$PORT
ENVEOF
chmod 600 .env

# --- 3. dependencies + prisma engine ---------------------------------------
if [ ! -x node_modules/.bin/next ]; then
  echo "[3] node_modules missing — running npm install ..."
  npm install --no-audit --no-fund --loglevel=error
else
  echo "[3] node_modules present — skipping npm install"
fi
echo "    prisma generate ..."
./node_modules/.bin/prisma generate >/dev/null 2>&1 && echo "    OK" || echo "    prisma generate reported an issue (continuing)"

# --- 4. CLEAN reseed: drop every table, re-import fresh ---------------------
if [ -f spincraft.sql.gz ]; then
  echo "[4] cleaning database (dropping all tables) ..."
  DROPS=$(mysql -u "$DBU" -p"$DBP" "$DBN" -N -e \
    "SET group_concat_max_len=1000000; \
     SELECT GROUP_CONCAT('\`', table_name, '\`') \
     FROM information_schema.tables WHERE table_schema='$DBN';" 2>/dev/null)
  if [ -n "$DROPS" ] && [ "$DROPS" != "NULL" ]; then
    mysql -u "$DBU" -p"$DBP" "$DBN" -e "SET FOREIGN_KEY_CHECKS=0; DROP TABLE IF EXISTS $DROPS; SET FOREIGN_KEY_CHECKS=1;" \
      && echo "    dropped old tables"
  fi
  echo "    importing fresh schema + data ..."
  gunzip -c spincraft.sql.gz | mysql -u "$DBU" -p"$DBP" "$DBN" && echo "    imported clean"
else
  echo "[4] spincraft.sql.gz not present — keeping existing data"
fi
echo "    tables now: $(mysql -u "$DBU" -p"$DBP" "$DBN" -N -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$DBN';" 2>/dev/null)"

# --- 5. all logins -> admin123 (clean, known state) ------------------------
echo "[5] setting all passwords to admin123 ..."
mysql -u "$DBU" -p"$DBP" "$DBN" -e "UPDATE User SET passwordHash='$ADMIN_HASH';" 2>&1
echo "    users total: $(mysql -u "$DBU" -p"$DBP" "$DBN" -N -e 'SELECT COUNT(*) FROM User;' 2>/dev/null)"

# --- 6. apache reverse proxy -----------------------------------------------
echo "[6] writing .htaccess proxy -> 127.0.0.1:$PORT ..."
cat > .htaccess <<HTEOF
RewriteEngine On
DirectoryIndex disabled
RewriteRule ^/?\$ http://127.0.0.1:$PORT/ [P,L,QSA]
RewriteRule ^(.+)\$ http://127.0.0.1:$PORT/\$1 [P,L,QSA]
PassengerEnabled off
HTEOF

# --- 7. keepalive helper + cron --------------------------------------------
cat > keepalive.sh <<KAEOF
#!/bin/bash
cd $APP || exit 0
[ -f node.pid ] && kill -0 "\$(cat node.pid)" 2>/dev/null && exit 0
export PATH=$NODEBIN:\$PATH
export HOME=/home/erpsolution26
export NODE_ENV=production
setsid nohup ./node_modules/.bin/next start -p $PORT >> node.log 2>&1 &
echo \$! > node.pid
KAEOF
chmod +x keepalive.sh
# add keepalive cron once
if command -v crontab >/dev/null 2>&1; then
  ( crontab -l 2>/dev/null | grep -v "$APP/keepalive.sh"; \
    echo "* * * * * /bin/bash $APP/keepalive.sh >/dev/null 2>&1" ) | crontab - 2>/dev/null \
    && echo "[7] keepalive cron installed"
fi

# --- 8. (re)start the app --------------------------------------------------
echo "[8] starting node ..."
: > node.log
setsid nohup ./node_modules/.bin/next start -p $PORT >> node.log 2>&1 &
echo $! > node.pid
echo "    pid $(cat node.pid)"

# --- 9. verify -------------------------------------------------------------
CODE=000
for i in $(seq 1 40); do
  sleep 3
  CODE=$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:$PORT/login 2>/dev/null)
  [ "$CODE" = "200" ] && break
done
echo "[9] local /login  -> $CODE"
LOGIN=$(curl -s -X POST http://127.0.0.1:$PORT/api/auth/login \
        -H 'Content-Type: application/json' \
        --data '{"email":"admin@spincraft.com","password":"admin123"}' \
        -w ' [HTTP %{http_code}]' 2>/dev/null)
echo "    admin login test: $LOGIN"
echo ""
if echo "$LOGIN" | grep -q 'HTTP 200'; then
  echo "============================================================"
  echo " SUCCESS — sign in at:  https://spincraft.erpsolution26.com/login"
  echo "   admin@spincraft.com  /  admin123   (all 9 demo users use admin123)"
  echo "============================================================"
else
  echo "!! Login not confirmed yet. Show me the output above and node.log:"
  echo "   tail -30 $APP/node.log"
fi
echo "================ done  $(date) ================"
