#!/usr/bin/env bash
set -e

FRONTEND_DIR="/home/swire/sociowire-frontend"
BUILD_DIR="$FRONTEND_DIR/dist"
NGINX_TARGET="/var/www/sociowire"

echo "======================================="
echo "   SocioWire FRONTEND DEPLOY START     "
echo "======================================="

cd "$FRONTEND_DIR"

echo "[1/5] Pulling last version..."
git pull

echo "[2/5] Checking Node versions..."
echo "Node: $(node -v || echo 'NOT FOUND')"
echo "npm : $(npm -v || echo 'NOT FOUND')"

if ! command -v node >/dev/null; then
  echo "ERROR: NodeJS not found in PATH."
  exit 1
fi

if ! command -v npm >/dev/null; then
  echo "ERROR: npm not found in PATH."
  exit 1
fi

echo "[3/5] Installing dependencies..."
npm install --silent

echo "[4/5] Building frontend..."
npm run build

echo "[5/5] Deploying to Nginx directory..."
sudo mkdir -p "$NGINX_TARGET"
sudo rm -rf "$NGINX_TARGET"/*
sudo cp -r "$BUILD_DIR"/* "$NGINX_TARGET"

echo "Restarting nginx..."
sudo systemctl restart nginx

echo "======================================="
echo "   FRONTEND DEPLOY SUCCESSFUL 🎉       "
echo "======================================="
