#!/bin/bash

declare -r DEV="${1}"
declare STARTDATE=""
declare STARTDATESTRING=""

show_help() {
	echo "ddwipe dev (/dev/sdX)"
	echo ""
	echo "Version : 0.0.3"
}

check_args() {
	if [ "${1}" == "" ]; then
		show_help
		exit 1
	fi
}

check_dev_exist() {
	if [ ! -e "${1}" ]; then
		echo "${1} is missing."
		exit 1
	fi
}

confirm_wipe() {
	lsblk "${1}"
	echo ""
	read -r -p "Wipe ${1} (y/[n])?" CHOICE
	case "${CHOICE}" in 
		y|Y ) echo "";;
		* )
			echo "Canceled"
			exit 1
		;;
	esac
}

wipe_dev() {
	STARTDATE=$(date +%s)
	STARTDATESTRING="$(date)"
	echo "Begin wiping device ${1}"
	echo ""
	echo "Start date :"
	echo "${STARTDATESTRING}"
	echo ""
	echo "blkdiscard secure"
	if ! blkdiscard -f -p 500M -s -v "${1}"; then
		echo ""
		echo "blkdiscard zero"
		if ! blkdiscard -f -p 500M -z -v "${1}"; then
			echo ""
			echo "dd zero"
			if ! dd if=/dev/zero of="${1}" bs=1M status=progress; then
				# Need check if dd has all writed, if yes, return no error
				# echo "Error wiping device ${1}, use phisical destroy !"
				echo "Wiped with dd, check if full size is writed."
				echo "Otherwise use a mechanical destruction of the device."
				print_time
				exit 1
			fi
		fi
	fi
	echo ""
	echo "Device ${1} wipped !"
}

print_time() {
	echo ""
	echo "Start date :"
	echo "${STARTDATESTRING}"
	
	ENDDATE=$(date +%s)
	echo ""
	echo "End date :"
	date

	CALCTIME=$((ENDDATE-STARTDATE))
	echo ""
	echo "Total time :"
	date -d@${CALCTIME} -u +%H:%M:%S
}

check_args "${DEV}"
check_dev_exist "${DEV}"
confirm_wipe "${DEV}"
wipe_dev "${DEV}"
print_time
