#!/bin/sh

# Linux Vulnerability Mitigation
# Copyright (C) 2026 Daniel Baumann <daniel@debian.org>
#
# SPDX-License-Identifier: PD
#
# This program is free software: you have unlimited permission
# to copy, distribute and modify it.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

set -e

PROGRAM="linux-vulnerability-mitigation"
COMMAND="$(basename "${0}")"

SHARE="/usr/share/${PROGRAM}"

if [ -t 1 ] && [ -t 2 ]
then
	RED="\033[1;33;31m"
	GREEN="\033[1;33;32m"
	NORMAL="\033[0m"
fi

Parameters ()
{
	GETOPT_LONGOPTIONS="mitigations:,help,"
	GETOPT_OPTIONS="m:,h,"

	PARAMETERS="$(getopt --longoptions ${GETOPT_LONGOPTIONS} --name="${COMMAND}" --options ${GETOPT_OPTIONS} --shell sh -- "${@}")"

	# shellcheck disable=SC2181
	if [ "${?}" != "0" ]
	then
		echo "'${COMMAND}': getopt exit" >&2
		exit 1
	fi

	eval set -- "${PARAMETERS}"

	while true
	do
		case "${1}" in
			-m|--mitigations)
				MITIGATIONS="${2}"
				shift 2
				;;

			-h|--help)
				Usage
				;;

			--)
				shift 1
				break
				;;

			*)
				echo "'${COMMAND}': getopt error" >&2
				exit 1
				;;
		esac
	done
}

Usage ()
{
	echo "Usage: ${PROGRAM} ${COMMAND} -m|--mitigation={MITIGATION|MITIGATION1,MITIGATION2,...|ALL}" >&2
	echo
	echo "See ${PROGRAM}-${COMMAND}(1), ${PROGRAM}(1) and ${PROGRAM}(7) for more information."
}

Parameters "${@}"

MITIGATIONS_RUN=""

for MITIGATION in ${MITIGATIONS}
do
	case "${MITIGATION}" in
		ALL)
			MITIGATIONS_RUN="$(find "${SHARE}/mitigations" -mindepth 1 -printf '%f\n' | sort -V)"
			;;
	esac
done

if [ -z "${MITIGATIONS_RUN}" ]
then
	if [ -n "${MITIGATIONS}" ]
	then
		MITIGATIONS_RUN="$(echo "${MITIGATIONS}" | sed -e 's|,| |g')"
	else
		Usage
		exit 1
	fi
fi

# Run
case "$(id -u)" in
	0)
		;;

	*)
		echo "${RED}error:${NORMAL} '${COMMAND}' operation requires superuser privilege" >&2
		exit 1
		;;
esac

for MITIGATION in ${MITIGATIONS_RUN}
do
	if [ ! -x "${SHARE}/mitigations/${MITIGATION}" ]
	then
		echo "${RED}error:${NORMAL} '${MITIGATION}' no such mitigation" >&2
		exit 1
	fi

	"${SHARE}/mitigations/${MITIGATION}" install

	echo "  ${GREEN}installing       ${NORMAL}  $(basename "${MITIGATION}")  $(awk -F= '/^DATE=/ { print $2 }' "${SHARE}/mitigations/${MITIGATION}")  $(awk -F= '/^NAME=/ { print $2 }' "${SHARE}/mitigations/${MITIGATION}")"
done
