#!/bin/bash PORT=4200 # Get absolute path to script SCRIPT_PATH="$(readlink -f "$0")" # Get directory containing the script SCRIPT_DIR="$(dirname "$SCRIPT_PATH")" # Set project directory PROJECT_DIR="$SCRIPT_DIR" LOG_FILE="$PROJECT_DIR/startup.log" # Function to log messages log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE" } # Navigate to the project directory cd "$PROJECT_DIR" || { log "Failed to navigate to project directory. Exiting." exit 1 } log "Starting NextJS application..." # Check if Node.js is installed if ! command -v node &> /dev/null; then log "Node.js is not installed. Please install Node.js and try again." exit 1 fi # Check if yarn or npm is installed if command -v yarn &> /dev/null; then PKG_MANAGER="yarn" elif command -v npm &> /dev/null; then PKG_MANAGER="npm" else log "Neither yarn nor npm is installed. Please install a package manager and try again." exit 1 fi log "Using $PKG_MANAGER as package manager" # Install dependencies if node_modules doesn't exist if [ ! -d "node_modules" ]; then log "Installing dependencies..." if [ "$PKG_MANAGER" = "yarn" ]; then yarn install else npm install fi if [ $? -ne 0 ]; then log "Failed to install dependencies. Exiting." exit 1 fi log "Dependencies installed successfully" fi # Build the application log "Building the application..." if [ "$PKG_MANAGER" = "yarn" ]; then yarn build else npm run build fi if [ $? -ne 0 ]; then log "Build failed. Exiting." exit 1 fi log "Build completed successfully" # Check if the PORT environment variable is set if [ -z "$PORT" ]; then PORT=3000 log "PORT not specified, using default port $PORT" else log "Using port $PORT" fi # Start the application log "Starting the application on port $PORT..." if [ "$PKG_MANAGER" = "yarn" ]; then PORT=$PORT yarn start else PORT=$PORT npm start fi # This part will only be reached if the application crashes log "Application terminated unexpectedly or killed." exit 1