#!/bin/bash

if ! [ -d /etc/munin/plugins ]; then
	echo "Munin plugins dir doesn't exist"
	exit 3
fi

if ! [ -d /dev/disk/by-id ]; then
	echo "Physical disks don't exist in /dev/disk/by-id"
	exit 5
fi

CHG=0

munin_disks=`find /etc/munin/plugins/ -type l -name 'smart*' -regex '^\/etc\/munin\/plugins\/smart_.*$' |sed -e 's/\/etc\/munin\/plugins\/smart_//'`

for mdisk in $munin_disks; do
#	echo "checking $mdisk"
	if ! [ -L /dev/disk/by-id/${mdisk} ]; then
		echo "Removing non-existing disk ${mdisk}"
		rm /etc/munin/plugins/smart_${mdisk}
		CHG=1
	fi
done

smart_disks=`find /dev/disk/by-id/ -type l -regex '^\/dev\/disk\/by-id\/\(ata\|nvme\|scsi\)-.*$' |grep -ve '-part.*$' |grep -oe '\(ata\|nvme\|scsi\)-.*'`

for sdisk in $smart_disks; do
#	echo "$sdisk"
	if ! [ -L /etc/munin/plugins/smart_${sdisk} ]; then
		echo "Adding disk ${sdisk}"
		ln -s /usr/share/munin/plugins/smart_ /etc\/munin\/plugins\/smart_${sdisk}
		CHG=1
	fi
done

if [ "x$CHG" == "x1" ]; then
	if (pidof systemd >/dev/null); then
		systemctl restart munin-node
		systemctl status munin-node
	else
		/etc/init.d/munin-node restart
	fi
fi
