#!/bin/bash
# # Script Name: usbclean
# Description: Erase, formating and partitioning of USB-Sticks
#
# Copyright (C) 2020-2025 by Intevation GmbH
# Authors:
#  Benedikt Tuchen <benedikt@intevation.de>
#  Thomas Arendsen Hein <thomas@intevation.de>
#
# This program is free software under the GNU GPL (>=v2)
# -------------------------------------------------------------------

# Exit when any command fails
set -e
# Keep track of the last executed command
last_command=""; current_command=""
trap 'last_command=$current_command; current_command=$BASH_COMMAND' DEBUG
# Echo an error message before exiting
trap 'rc="$?"; test "$rc" -ne 0 && echo "\"${last_command}\" command failed with exit code $rc."' EXIT

usage() {
  echo "Usage: usbclean <device> <label>"
  echo
  echo 'Example: usbclean /dev/sdx "flash"'
  echo "-h or --help"
  echo "     Print this help message"
}

if [[ "$1" = "-h" ]] || [[ "$1" = "--help" ]]
then
  usage
  exit 0
fi

if [[ $# -ne 2 ]]
then
  usage >&2
  exit 1
fi

# ARG variables
device=$1
partition=${device}1
label=$(tr "a-z" "A-Z" <<< "$2")

# Script based variables
usbcheck=$(find /dev/disk/by-id -name 'usb-*' -not -regex '.*-part[0-9]+$' \
  -printf '%l\n'|sed 's|../..|/dev|')

# Check if $device is a usb-drive
if ! grep -Fxq "$usbcheck" <<< "$device"
then
  echo "ERROR:"
  echo "Your choosen device \"$device\" is not a usb-drive"
  exit 1
fi

# Partitions shouldn't be mounted
if df | grep -q "^$device"
then
  echo "ERROR:"
  echo "Please unmount all partitions of the device before using this script"
  exit 1
fi

# Ask the user if he really wants to erase $device (using "ddrescue --ask")
echo "Do you really want to erase \"$device\" now?"
echo

# Erase flash
size="$(/sbin/blockdev --getsize64 "$device")"
ddrescue --ask --force --size "$size" /dev/zero "$device"

# Partitioning with fdisk
echo ',,c;' | /sbin/sfdisk --no-tell-kernel "$device"

# Wait for partitioning to appear
sleep 2

# Format the partition and add a label
/sbin/mkfs.vfat -F32 -n "$label" "$partition"
echo

# Display file information for quick check
file -s "${partition}"

exit 0
