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

# Requirements
REQUIRED_SPACE_GB="10"
REQUIRED_MEMORY_GB="6"

# We need to kill the parent install process because exiting this script
# only kills the current hook process not the parent. The user won't get
# any visual feedback if we exit but it's better than letting them kill
# their system.
kill_app_install() {
  pkill --full "app install llama-gpt"
  exit 1
}

# Check available space
REQUIRED_SPACE_KB=$((REQUIRED_SPACE_GB * 1024 * 1024))
UMBREL_ROOT="$(readlink -f $(dirname "${BASH_SOURCE[0]}")/../../..)"
AVAILABLE_SPACE_KB=$(df "${UMBREL_ROOT}" | tail -1 | awk '{print $4}')
if (( AVAILABLE_SPACE_KB < REQUIRED_SPACE_KB ))
then
    echo "Not enough available storage space to install LlamaGPT. Exiting."
    kill_app_install
fi

# Check available memory
REQUIRED_MEMORY_KB=$((REQUIRED_MEMORY_GB * 1024 * 1024))
TOTAL_MEMORY_KB=$(free | grep '^Mem' | awk '{print $2}')
if (( TOTAL_MEMORY_KB < REQUIRED_MEMORY_KB ))
then
    echo "Not enough system memory to install LlamaGPT. Exiting."
    kill_app_install
fi