#!/bin/bash
exec &> >(while read line; do logger -t "$0"  -i -- "$line"; done)
set -x

lspci=$(which lspci)
nvme=$(which nvme)

if [[ ! -e $lspci || ! -e $nvme ]]; then echo "missing lspci or nvme command"; exit 1; fi

chknvme=$(${nvme} list | grep "SAMSUNG MZ1L2960HCJR-00A07" | wc -l)

if [ $chknvme -eq 1 ]; then
#  udev=$(${lspci} | grep "Non-Volatile" | grep "Samsung" | egrep "PM9A1|980PRO|a80a" | awk '{print $1}')
  udev=$(${lspci} | grep "Non-Volatile" | grep "Samsung" | awk '{print $1}')
  speed=3
  script=/opt/pcie_set_speed.sh
  this=$(basename $0)

  if [ -z "$udev" ]; then
        echo "PM9A1 drive not found via lspci";
        exit 1;
  fi

  echo "PM9A1 drive detected @ $udev"

  if [[ -e $script && -s $script ]]; then
    if [ ! -x $script ]; then
      chmod a+x $script
    fi
    $script $udev $speed
  else
    echo "$script file not exist"
    exit 1
  fi

  h=$(hostname)
  if [ "$h" != "debian" ]; then
    if ! grep -q -F "$this" /etc/crontab; then
      echo "@reboot root /opt/pcie_pm9a1.sh 2>&1" >> /etc/crontab
    fi
  fi
else
  echo "PM9A1 drive not found"
fi
