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

source ./scripts/Unix/starter.sh

if [ ! -f .env ]; then
  echo ".env file not found. Exiting without running Docker steps." >&2
  exit 0
fi

cpu_count=$(getconf _NPROCESSORS_ONLN)
if [ "$cpu_count" -lt 4 ]; then
  exit 1
fi

if [ -f /proc/meminfo ]; then
  mem_kb=$(grep MemTotal /proc/meminfo | awk '{print $2}')
  total_mem_gb=$(awk "BEGIN {printf \"%.2f\", $mem_kb/1024/1024}")
else
  total_mem_bytes=$(sysctl -n hw.memsize)
  total_mem_gb=$(awk "BEGIN {printf \"%.2f\", $total_mem_bytes/1024/1024/1024}")
fi
if ! awk "BEGIN {exit !($total_mem_gb >= 6)}"; then
  exit 1
fi

avail_kb=$(df -k . | tail -1 | awk '{print $4}')
free_gb=$(awk "BEGIN {printf \"%.2f\", $avail_kb/1024/1024}")
if ! awk "BEGIN {exit !($free_gb >= 20)}"; then
  exit 1
fi

echo "System requirements met: CPU cores=$cpu_count, RAM=${total_mem_gb}GB, FreeDisk=${free_gb}GB"

echo "Pulling images"
docker compose pull
echo "Images pulled successfully"

echo "Building images"
docker compose build
echo "Images built successfully"

echo
echo "You can now use run.sh script."
