#!/bin/bash
set -e

############################################
# PART 1 — BASIC SERVER + NODE + X-UI SETUP
############################################

echo "==> Setting root password..."
echo "root:Moqol2424!!" | chpasswd

echo "==> Updating package index..."
apt update

echo "==> Installing base packages..."
apt install -y curl git vnstat

echo "==> Installing Node.js LTS..."
curl -fsSL https://deb.nodesource.com/setup_lts.x | bash -
apt-get install -y nodejs

echo "==> Installing pm2 globally..."
npm install -g pm2

echo "==> Verifying Node / npm / pm2 versions..."
node_version=$(node -v)
npm_version=$(npm -v)
pm2_version=$(pm2 -v)

echo "Node.js version: $node_version"
echo "npm version:     $npm_version"
echo "pm2 version:    $pm2_version"

echo "==> Cloning x-ui project..."
cd /usr/local/

if [ ! -d "x-ui" ]; then
  git clone http://git.fcfglobal.co/root/x-ui.git
else
  echo "x-ui already exists, skipping clone."
fi

cd x-ui

echo "==> Setting permissions..."
chmod 777 xray

echo "==> Installing project dependencies..."
npm install

echo "==> Starting project with pm2..."
pm2 startup
pm2 start app.json
pm2 save

echo "==> x-ui setup completed successfully."
