#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

# Update package lists
echo "Updating package lists..."
sudo apt-get update

# Install Git
echo "Installing Git..."
sudo apt-get install -y git

# Install build-essential for gcc/g++
echo "Installing build-essential (gcc/g++)..."
sudo apt-get install -y build-essential

# Install Node.js (using NodeSource for the latest version)
echo "Installing Node.js..."
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs

# Install Python 3.10 or later and python-is-python3
echo "Installing Python 3.10 or later and python-is-python3..."
sudo apt-get install -y python3 python3-pip python-is-python3

# Verify the installations
echo "Verifying installations..."

GIT_VERSION=$(git --version)
NODE_VERSION=$(node -v)
NPM_VERSION=$(npm -v)
PYTHON_VERSION=$(python --version)
GCC_VERSION=$(gcc --version | head -n 1)
GPP_VERSION=$(g++ --version | head -n 1)

if [[ ! $GIT_VERSION ]]; then
    echo "Git is not installed correctly."
    exit 1
fi

if [[ ! $NODE_VERSION =~ ^v18\.[0-9]+\.[0-9]+$ ]]; then
    echo "Node.js version is not 18.x.x."
    exit 1
fi

if [[ ! $NPM_VERSION ]]; then
    echo "npm is not installed correctly."
    exit 1
fi

if [[ ! $PYTHON_VERSION =~ ^Python\ 3\.(10|[1-9][1-9])\.[0-9]+$ ]]; then
    echo "Python version is not 3.10 or later."
    exit 1
fi

if [[ ! $GCC_VERSION =~ ^gcc ]]; then
    echo "GCC is not installed correctly."
    exit 1
fi

if [[ ! $GPP_VERSION =~ ^g\+\+ ]]; then
    echo "G++ is not installed correctly."
    exit 1
fi

echo "Git version: $GIT_VERSION"
echo "Node.js version: $NODE_VERSION"
echo "npm version: $NPM_VERSION"
echo "Python version: $PYTHON_VERSION"
echo "GCC version: $GCC_VERSION"
echo "G++ version: $GPP_VERSION"

# Clone the Spacebar repository with progress displayed
echo "Cloning the Spacebar repository..."
git clone --progress https://github.com/spacebarchat/server.git

# Navigate to project root
cd server

# Install JavaScript packages
echo "Installing JavaScript packages..."
npm i

# Build and generate schema
echo "Building and generating schema..."
npm run setup

# Start the bundle server
echo "Starting the bundle server..."
npm run start &

# Wait for a few seconds to ensure the server has started
sleep 10

# Verify the server is up
echo "Verifying the server is up..."
CURL_OUTPUT=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3001/api/ping)

if [[ $CURL_OUTPUT -eq 200 ]]; then
    echo "Server is up and running. Response: $CURL_OUTPUT"
else
    echo "Failed to verify the server is running. Response: $CURL_OUTPUT"
    exit 1
fi

echo "Setup complete. The Spacebar server is running."
