#!/bin/bash

USE_KDUMP="no"

if [ $# -eq 0 ]; then
	# CPU/RAM Criteria
	MIN_CPU_THREADS=4
	MIN_MEMORY_GB=6
	MAX_MEMORY_GB=2048

	# Get current CPU threads and RAM available
	CPU_THREADS=$(grep -c processor /proc/cpuinfo)
	RAM_GB=$(grep MemTotal /proc/meminfo | awk '{print int($2 / 1024 / 1024)}')
	SWAP_GB=$(grep SwapTotal /proc/meminfo | awk '{print int($2 / 1024 / 1024)}')
	MEMORY_GB=$((RAM_GB+SWAP_GB))

	# CPU Architecture Criteria
	CPU_ARCHES_SUPPORTED=( "x86_64" "aarch64" "s390x")

	# Get CPU architecture
	CPU_ARCH=$(uname -p)

	# Calculate minimum free space in /var and current free space in /var
	VAR_FREE_SPACE_MULTIPLE=5
	MIN_VAR_FREE_GB=$((VAR_FREE_SPACE_MULTIPLE*MEMORY_GB))
	VAR_FREE_GB=$(df --output=avail -BG /var | tail -n 1 | sed 's/[^0-9]*$//')

	# No arguments. Determine if we meet criteria to enable by default
	echo "KDump Default Enablement Criteria: CPU Architectures: ${CPU_ARCHES_SUPPORTED[*]}, CPU Threads >= $MIN_CPU_THREADS, RAM/Swap: $MIN_MEMORY_GB-$MAX_MEMORY_GB GB, Free Space in /var >= ${VAR_FREE_SPACE_MULTIPLE}x RAM/Swap ($MIN_VAR_FREE_GB GB)"
	echo -n "Hardware Found: CPU Architecture: $CPU_ARCH, CPU Threads: $CPU_THREADS, Memory: "
	if [ "$MEMORY_GB" -lt 1 ]; then
		echo -n "<1"
	else
		echo -n "$MEMORY_GB"
	fi
	echo -n " GB, Free space in /var: "
	if [ "$VAR_FREE_GB" -lt 1 ]; then
		echo -n "<1"
	else
		echo -n "$VAR_FREE_GB"
		echo " GB"
	fi

	if [ "$CPU_THREADS" -ge "$MIN_CPU_THREADS" ] \
		&& [ "$MEMORY_GB" -ge "$MIN_MEMORY_GB" ] \
		&& [ "$MEMORY_GB" -le "$MAX_MEMORY_GB" ] \
		&& [ "$VAR_FREE_GB" -gt "$MIN_VAR_FREE_GB" ] \
		&& [ "$(echo "${CPU_ARCHES_SUPPORTED[*]}" | grep -ow "$CPU_ARCH" | wc -w)" -gt 0 ]; then
		USE_KDUMP="yes"
	else
		USE_KDUMP="no"
	fi
elif [ "$1" = "true" ]; then
	# Use argument to enable
	USE_KDUMP="yes"
elif [ "$1" = "false" ]; then
	# Use argument to disable
	USE_KDUMP="no"
fi

if [ "$USE_KDUMP" = "yes" ]; then
	echo "KDump will be enabled."
else
	echo "KDump will be disabled."
fi

EDITOR="sed -Ei 's|^(kdump-tools/use_kdump)=.+|\1=\"$USE_KDUMP\"|'" dpkg-reconfigure -f editor kdump-tools
