#!/usr/bin/env bash
set -euo pipefail

if [ ! -d "./evibes" ]; then
  printf "\e[31m❌  Please run this script from the project's root (where the 'evibes' directory lives).\e[0m\n"
  exit 1
fi

PURPLE="\e[38;2;121;101;209m"
RESET="\e[0m"
GRAY="\e[90m"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ART_PATH="$SCRIPT_DIR/../ASCII_ART_EVIBES"

if [ ! -f "$ART_PATH" ]; then
  printf "\e[31m❌  Could not find ASCII art at %s\e[0m\n" "$ART_PATH"
  exit 1
fi

while IFS= read -r line; do
  printf "%b%s%b\n" "$PURPLE" "$line" "$RESET"
done < "$ART_PATH"

printf "\n%b                                                                       by WISELESS TEAM%b\n\n" "$GRAY" "$RESET"

if [ ! -f .env ]; then
  printf "\e[33m.env file not found. Exiting without running Docker steps.\e[0m\n"
  exit 0
fi

CPU_COUNT=$(nproc 2>/dev/null || sysctl -n hw.ncpu)
if [ "$CPU_COUNT" -lt 4 ]; then
  printf "\e[31mInsufficient CPU cores: %d detected. Minimum 4 required.\e[0m\n" "$CPU_COUNT"
  exit 1
fi

if [ -f /proc/meminfo ]; then
  MEM_KB=$(awk '/MemTotal/ {print $2}' /proc/meminfo)
  MEM_GB=$(awk "BEGIN {printf \"%.2f\", ${MEM_KB}/1024/1024}")
else
  MEM_BYTES=$(vm_stat | awk '/Pages free/ {print $3 * 4096}')
  MEM_GB=$(awk "BEGIN {printf \"%.2f\", ${MEM_BYTES}/1024/1024/1024}")
fi

if (( $(echo "$MEM_GB < 6" | bc -l) )); then
  printf "\e[31mInsufficient RAM: %.2fGB detected. Minimum 6 GB required.\e[0m\n" "$MEM_GB"
  exit 1
fi

FREE_GB=$(df -BG . | awk 'NR==2 {gsub("G","",$4); print $4}')
if [ "$FREE_GB" -lt 20 ]; then
  printf "\e[31mInsufficient free disk space: %dGB available. Minimum 20 GB required.\e[0m\n" "$FREE_GB"
  exit 1
fi

printf "\e[32mSystem requirements met: CPU cores=%d, RAM=%.2fGB, FreeDisk=%dGB\e[0m\n" "$CPU_COUNT" "$MEM_GB" "$FREE_GB"

printf "\e[36mPulling related images…\e[0m\n"
docker compose pull

printf "\e[36mBuilding the project's images…\e[0m\n"
docker compose build
