#!/usr/bin/env bash

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
BINUTILS_DIR="$SCRIPT_DIR/objdir/usr/local/bin"

quiet=''
while getopts "b" opt; do
    case $opt in
        b) quiet='1';;
    esac
done

# Confirm 64-bit architecture
if [ `uname -m` != 'x86_64' ]; then
    echo "Error: This build of MemSQL requires an x86_64 (amd64) architecture." 1>&2
    exit 1
fi

# Check Minimum Memory
let "mem_mb=$(free -m | perl -ne 'print "$1\n" if /Mem:[^0-9]*([0-9]*)/')";
if [ $mem_mb -lt 7900 ]; then
    echo "Warning: The recommended configuration for MemSQL is at least 8 GB of RAM." 1>&2
    invalid='1'
fi

# Check ulimit
ulimit_docs='https://docs.memsql.com/docs/installation-best-practices#configure-linux-ulimit-setting'
if [ `ulimit -n` != 'unlimited' ] && [ `ulimit -n` -lt 64000 ]; then
    echo "Warning: The number of allowed open file descriptors should be at least 64000. This OS is currently configured with the limit set to" "`ulimit -n`"". Please visit $ulimit_docs"
fi
if [ `ulimit -u` != 'unlimited' ] && [ `ulimit -u` -lt 128000 ]; then
    echo "Warning: The number of allowed user processes should be at least 128000. This OS is currently configured with the limit set to" "`ulimit -u`"". Please visit $ulimit_docs"
fi

# Check hardware crc32 support
if [[ -d $SCRIPT_DIR/lib ]]; then
    LD_LIBRARY_PATH=$SCRIPT_DIR/objdir/usr/local/lib64 $SCRIPT_DIR/lib/check_crc32 > /dev/null 2> /dev/null
else
    LD_LIBRARY_PATH=$SCRIPT_DIR/objdir/usr/local/lib64 $SCRIPT_DIR/check_crc32/check_crc32
fi
if [[ $? != 0 ]]; then
    echo "Warning: SSE4.2 is not supported. Resorting to software CRC32C. MemSQL recovery and log writing performance will be negatively impacted."
    exit 2
fi

if [[ -z $quiet && -z $invalid ]]; then
    echo "System check successful" 1>&2
fi
