#!/bin/bash

## Copyright (C) 2012 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

check_spectre_meltdown() {
   local spectre_meltdown_checker_output spectre_meltdown_checker_exit_code
   local file_name timeout_after kill_after

   local if_you_know_what_you_are_doing_msg
   if_you_know_what_you_are_doing_msg="$(if_you_know_what_you_are_doing_funct "$FUNCNAME")"

   if [ "$verbose" -ge "2" ]; then
      [ -n "$spectre_meltdown_check" ] || spectre_meltdown_check="true"
   fi

   [ -n "$spectre_meltdown_check" ] || spectre_meltdown_check="false"

   if [ "$spectre_meltdown_check" = "false" ]; then
      local MSG="<p>Spectre Meltdown Test: skipping since spectre_meltdown_check=<code>$spectre_meltdown_check</code>, ok.</p>"
      if [ "$verbose" -ge "1" ]; then
         $output_x ${output_opts[@]} --messagex --typex "info" --message "$MSG"
         $output_cli ${output_opts[@]} --messagecli --typecli "info" --message "$MSG"
      fi
      return 0
   fi

   spectre_meltdown_checker_exit_code="0"
   timeout_after="10"
   kill_after="10"

   spectre_meltdown_checker_output="$(timeout --kill-after="$kill_after" "$timeout_after" leaprun spectre-meltdown-checker 2>&1)" || { spectre_meltdown_checker_exit_code="$?"; };

   if [ "$spectre_meltdown_checker_exit_code" = "0" ]; then
      local MSG="<p>Spectre Meltdown Test Result: not vulnerable, ok.</p>"
      if [ "$verbose" -ge "1" ]; then
         $output_x ${output_opts[@]} --messagex --typex "info" --message "$MSG"
         $output_cli ${output_opts[@]} --messagecli --typecli "info" --message "$MSG"
      fi
   else
      local MSG="<p>Spectre Meltdown Test Result: Vulnerable.<br />
<br />
Technical information:<br />
<code>spectre-meltdown-checker --paranoid</code><br />
exited with code <code>$spectre_meltdown_checker_exit_code</code>.<br />
<br />
Recommendation:<br />
See <a href=${PROJECT_HOMEPAGE}/wiki/Spectre_Meltdown>${PROJECT_HOMEPAGE}/wiki/Spectre_Meltdown</a>.<br />
<br />
$if_you_know_what_you_are_doing_msg</p>"
      $output_x ${output_opts[@]} --messagex --typex "warning" --message "$MSG"
      $output_cli ${output_opts[@]} --messagecli --typecli "warning" --message "$MSG"
      EXIT_CODE="1"
   fi
}
