#!/bin/bash

# Force sudo
[[ $EUID -ne  0 ]] && exec sudo "$0"

# Validate Machine
product="$(dmidecode -s 'system-version')"
if [[ "${product^^}" != *'24IAH7'* ]]; then
  printf "%s\n" 'ERROR: This patch is only compatible with Lenovo 24IAH7 machines.' \
  "Current System: ${product}" >&2
  exit 1
fi

# Validate Adapter
readarray -t networkHardware <<< "$(lshw -short -C network)"
if [[ "${networkHardware[2]}" != *'Intel Corporation'* ]];
  echo 'ERROR: Unrecognized or unfixable adapter' >&2
  exit 1
fi

# Set Vars
kernelRelease="$(uname -r)"
targetPackage="linux-modules-iwlwifi-${kernelRelease}"

# Ensure not already installed
installedVersion="$(apt-cache policy "${targetPackage}" | grep -Po '^\s*Installed: \K.*$')"
if [[ "${installedVersion}" != *'none'* ]]; then
  echo 'Appropriate patch already installed. Aborting' >&2
  exit 1
fi

# Ensure available.
if [[ -z "$(apt-cache policy "${targetPackage}" | grep 'Candidate')" ]]; then
  # If not available, offer option to update apt along with warning.
  echo 'The required patch is not immediately available, and checking remote servers for updates may have unintended consequences.'
  read -er -n1 -t30 -p "Do you want to attempt an update anyway? [y/N] " choice || choice='n'
  [[ "$choice" != [Yy]* ]] && echo 'Aborting. No update or patch performed.' >&2 && exit 1
  # Attempt the update and re-check for availability
  apt-get update &>/dev/null
  [[ -z "$(apt-cache policy "${targetPackage}" | grep 'Candidate')" ]] && echo 'Required patch still not available. Aborting.' >&2 && exit 1
fi

# Apply Fix
apt-get install -y "${targetPackage}"
echo 'Patch deployed. Reboot required.'
exit 0
