#!/usr/bin/env bash

. /usr/share/dosis2/bin/shell-support-functions

FILE_EXT="tar"
USB_LABEL="SYSRESC"

function cleanup() {
	echo "Cleaning up..."
}
trap cleanup EXIT

function die() {
    echo -e "$1"
    exit 1
}

function sanitizedhostname() {
	echo `hostname | cut -d '.' -f 1 | sed -e "s/-/_/g"`
}

if [[ -z "${FILE}" ]]; then
	FILE=`sanitizedhostname`.${FILE_EXT}
fi

if [[ -z "${MOUNTDIR}" ]]; then
	MOUNTDIR=/mnt/`sanitizedhostname`-step3a
fi

function getdevice() {
	sdx_temp=`ls /dev/sd*`
	for dev in ${sdx_temp}; do
	    if [[ ${dev} =~ ^/dev/sd[a-z]+$ ]]; then
	        SDX_DEVICES="${SDX_DEVICES} ${dev}"
	    fi
	done

	REMOVABLES=
	for dev in ${SDX_DEVICES}; do
	    removable=$(udevadm info --query=property --name=`basename ${dev}` | grep ID_BUS=usb)
	    if [[ $? = 0 ]]; then
	        REMOVABLES="${REMOVABLES} ${dev}"
	    fi
	done

	LABELED_PARTITIONS=
	LABELED_PARTITIONS_COUNT=0
	if [[ ! -z "${REMOVABLES}" ]]; then
	    for rem in ${REMOVABLES}; do
	    	remparts=`ls ${rem}* | egrep "${rem}[1-9]+"`
	    	for part in ${remparts}; do
	        	label=`blkid ${part} -o udev | grep ID_FS_LABEL= | cut -d '=' -f 2`
	        	if [[ "${label}" = "${USB_LABEL}" ]]; then
	        	    LABELED_PARTITIONS="${LABELED_PARTITIONS} ${part}"
	        	    let LABELED_PARTITIONS_COUNT=LABELED_PARTITIONS_COUNT+1
	        	fi
	        done
	    done
	else
	    die "No Removable devices found!"
	fi

    if [[ ${LABELED_PARTITIONS_COUNT} -eq 0 ]]; then
        die "No $USB_LABEL partitions found, make sure you have a Manchac Technologies issued install key"
    elif [[ ${LABELED_PARTITIONS_COUNT} -gt 1 ]]; then
        ALLREMS=

        echo -e "\033[33mMore than 1 $USB_LABEL disk found, either remove all other devices"
        echo -e "with this label and restart this step, or choose the correct one\033[0m"
        echo ""
        echo "These are the removable disks I found:"
        echo "    Enter the device name 'DEVICE'    "
        echo ""
        echo "------------------------------------------------------"
        echo "|   DEVICE   |     LABEL     |        SIZE (GB)      |"
        echo "------------------------------------------------------"
        for rem in ${REMOVABLES}; do
            remparts=`ls ${rem}* | egrep "${rem}[1-9]+"`
            for part in ${remparts}; do
                size=`blockdev --getsize64 ${part}` || die "\033[31mPlease run this script as super user (i.e. sudo)\033[0m"
                label=`blkid ${part} -o udev | grep ID_FS_LABEL= | cut -d '=' -f 2`
                if [[ "${label}" = "${USB_LABEL}" ]]; then
                    ALLREMS="${ALLREMS} ${part}"
                    python3 -c "print(\"|{:^12}|{:^15}|{:^23}|\".format(\"${part}\",\"${label}\",\"%s %s\" % (round(int(\"${size}\") / 1073741824.0, 2), \"GB\")))"
                fi
            done
        done
        echo "------------------------------------------------------"

        OKAY=
        until [[ ${OKAY} = true ]]; do
            printf "Device Name: "
            read DEVICE

            for rem in ${ALLREMS}; do
                if [[ "${rem}" = "${DEVICE}" ]]; then
                    OKAY=true
                    break
                fi
            done

            if [[ -z "${OKAY}" ]]; then
                echo -e "\033[31mBad Device Name... Enter one from the list I provided...\033[0m"
            fi
        done
    else
        DEVICE=$LABELED_PARTITIONS
    fi

	OKAY=
	printf "Device chosen \033[33m${DEVICE}\033[0m, continue? [y|n] "
	read OKAY

	if [[ ${OKAY} =~ [y|Y]([e|E][s|S])? ]]; then
	    OKAY=true
	else
	    die "Exiting on user command..."
	fi
}

# Get the device name that we want to use
# This will attempt to get the device named
# SYSRESC, but if there are multiple USB devices
# with the label SYSRESC, it will display all
# and ask the user to choose the correct one
getdevice

# Prepare the device for remount if applicable
umount -f ${DEVICE}
mkdir -p ${MOUNTDIR}

# Mount the directory or quit the program if it fails
mount ${DEVICE} ${MOUNTDIR} || die "Failed to mount device ${DEVICE}..."

# The VPN keys should be stored at the root of the USB key, with their associated
# <HOSTNAME>.tar format. This format will be used to fetch the key and extract it
# into the /etc/openvpn directory properly.
tar xvf ${MOUNTDIR}/${FILE} -C /etc/openvpn/. \
	|| die "Failed to extract \033[33m${MOUNTDIR}/${FILE}\033[0m to /etc/openvpn, please ensure it exist"

systemctl restart openvpn@dev_alex

watch -n2 'echo "wait for some tun interfaces to show up then hit CTRL+C";ifconfig tun0 2>/dev/null||echo "tun0 not available";ifconfig tun1 2>/dev/null||echo "tun1 not available"'

exit 0
