#!/bin/bash -e

# Checks that the hard drive is reachable and has the expected partitions
# Does not include a test for bad blocks

# Search for the internal disk

found=
for DEVICEID in sd{a..z} ; do
    type=`udevadm info /dev/${DEVICEID} 2> /dev/null | grep ID_BUS | cut -f2 -d=`
    if [ "$type" == "ata" ] ; then
        found=1
        break;
    fi
done

if [ -z ${found} ]; then
    echo "FAIL"
    echo "Hard drive not detected"
    echo "Check hard drive cable"
    exit 1
fi

USERID=$(id -u)
if [ "$USERID" != "0" ]; then
    echo "Program requires superuser privileges"
    exit 1
fi

DEVICE=/dev/${DEVICEID}

# Check the overall health of the drive
DRIVEPATH=$(gdbus call --system --dest org.freedesktop.UDisks2 --object-path /org/freedesktop/UDisks2/block_devices/${DEVICEID} --method org.freedesktop.DBus.Properties.Get 'org.freedesktop.UDisks2.Block' 'Drive' | cut -d "'" -f 2)
SMARTFAILING=$(gdbus call --system --dest org.freedesktop.UDisks2 --object-path ${DRIVEPATH} --method org.freedesktop.DBus.Properties.Get 'org.freedesktop.UDisks2.Drive.Ata' 'SmartFailing' | cut -d "<" -f 2 | cut -d ">" -f 1)
SMARTSELFTEST=$(gdbus call --system --dest org.freedesktop.UDisks2 --object-path ${DRIVEPATH} --method org.freedesktop.DBus.Properties.Get 'org.freedesktop.UDisks2.Drive.Ata' 'SmartSelftestStatus' | cut -d "'" -f 2)

if [ $SMARTFAILING != "false" -o $SMARTSELFTEST != "success" ]; then
    echo "FAIL"
    echo "Disk failed the overall health self-assessment test"
    echo "It may be necessary to replace the disk drive"
    echo "SMART Failing: $SMARTFAILING"
    echo "SMART Self Test result: $SMARTSELFTEST"
    exit 1
fi

# Note: don't check for the swap partition (eos-swap),
# since it is not created on smaller drives
LABELS="ostree-boot ostree"
PARTITION=1
for LABEL in $LABELS; do
    # Inlcude the quote symbol in the grep to match the exact label
    if ! blkid | grep -s $DEVICE$PARTITION | grep -qs \"$LABEL\"; then
        echo "FAIL"
        echo "Missing partition $DEVICE$PARTITION with label $LABEL"
        echo "It may be necessary to reflash the device"
        exit 1
    fi
    let PARTITION++
done

echo "PASS"
