#!/bin/bash

    << CHANGELOG
    2021-03-10: Initial Creation
    2021-03-11: Add slight delay between commands (ex: after mkfs.ext4) to prevent failures
    2022-12-12: Add explanation / equivalent command for Disk-02, and make mkdir verbose.
CHANGELOG


if [[ "$EUID" -ne 0 ]]; then
	echo "This installer needs to be run with superuser privileges."
	exit
fi




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Disk-01] - Basic Dependencies (Install parted)
$(tput sgr 0)
"

apt -qq update && apt -qq install -y parted




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Disk-02] - List unformatted / unpartitioned disks
$(tput sgr 0)
"
    # Source - https://stackoverflow.com/a/43890178/11295787
    
        : '
            What this does / is equivalent to:
                # [03-B] - Identify the New Disk
                sudo parted -l | grep unrecognised
        '

Devices=`lsblk -r --output NAME,MOUNTPOINT | awk -F \/ '/sd/ { dsk=substr($1,1,3);dsks[dsk]+=1 } END { for ( i in dsks ) { if (dsks[i]==1) print i } }'` && \
echo -e "$(tput setaf 7; tput setab 0)" && \
echo "Found Devices (/dev/sd*):" && \
echo ${Devices} && \
echo -e "$(tput sgr 0)"




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Disk-03] - Create Partition & Filesystem per unpartition disk
$(tput sgr 0)
"
    ## 'head -1' is to select only first result.
    ## '-F:' means split on ':' character

    # Loop over 'array' in bash - https://stackoverflow.com/a/1407098/11295787


for DeviceName in ${Devices}; do
    echo "-> Device: ${DeviceName}"

        : '
          What this does:
            # [03-C] - Choose Partition Table (GPT vs MBR)
            # [03-D] - Create the Partition
            # Verify partition created (i.e. Partition #1)
            # [03-E] - Create the Filesystem
            # Verify formatted successfully to ext4 filesystem
            # [03-F] - Auto-Mount on Boot with fstab using partition UUID
            # Test / Verify mounting
        '
    Device=/dev/${DeviceName} && \
    sudo parted ${Device} mklabel msdos && \
    sudo parted -a opt ${Device} mkpart primary ext4 0% 100% && \
    if (lsblk | grep "${DeviceName}1" > /dev/null); then
        sudo mkfs.ext4 "${Device}1" && \
        sleep 5 && \
        if (lsblk --fs | grep ext4 | grep "${DeviceName}1" > /dev/null); then
            UUID=$(sudo blkid -s UUID -o value "${Device}1") && \
            echo -e "$(tput setaf 7; tput setab 0)" && \
            echo "UUID: ${UUID}" && \
            echo -e "$(tput sgr 0)" && \
            sleep 5 && \
            if (sudo blkid | grep ${UUID} | grep "${DeviceName}1" > /dev/null); then
                MountPoint=/mnt/${DeviceName} && \
                echo -e "$(tput setaf 7; tput setab 0)" && \
                echo "Mount Point: ${MountPoint}" && \
                echo -e "$(tput sgr 0)" && \
                sudo mkdir -pv ${MountPoint} && \
                sleep 3 && \
                sudo chmod 777 "${MountPoint}" && \
                touch ${MountPoint}/NOT_MOUNTED_YET && \
                echo "/dev/disk/by-uuid/${UUID}   ${MountPoint}  ext4   defaults   0   0" | sudo tee -a /etc/fstab && \
                echo -e "$(tput setaf 7; tput setab 0)" && \
                echo "Preparing to mount..."
                sleep 10 && \
                mount -a && (df -h | grep ${MountPoint} ) && (lsblk -f | grep ${MountPoint}) && \
                echo -e "$(tput sgr 0)"
            else
                echo -e "$(tput setaf 0; tput setab 3)\nWarning: \n  UUID was not found in blkid output for device ${Device}... \n  Skipping fstab entry! $(tput sgr 0)"
            fi
        else
            echo -e "$(tput setaf 0; tput setab 3)\nWarning: \n  ext4 filesystem was not detected for device ${Device}... \n  Skipping fstab entry! $(tput sgr 0)"
        fi
    else
        echo -e "$(tput setaf 3; tput setab 1)\nError: \n  Partition 1 was not detected for device ${Device}... \n  Skipping filesystem creation! $(tput sgr 0)"
    fi
done

# Source - https://www.cyberciti.biz/faq/linux-modify-partition-labels-command-to-change-diskname/
echo -e "$(tput setaf 0; tput setab 2)\nDONE! \nTo add a label to a partition, use the command 'sudo e2label /dev/sdX1 LabelName'. $(tput sgr 0)"



echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-04] - Deployment Script Cleanup
$(tput sgr 0)
"

if ! command -v realpath &> /dev/null
then
    echo -e "COMMAND 'realpath' could not be found. $(tput setaf 3; tput setab 0)Please move script manually.$(tput sgr 0)"
else
    SCRIPT=`realpath -s $0` && \
    DESTINATION=~/Deploy && \
    mkdir -pv ${DESTINATION} && \
    mv ${SCRIPT} ${DESTINATION} && \
    ls -laR ${DESTINATION}
fi
