#!/bin/sh
#
# Purpose {{{
# This script will try to clean the content of the two firsts hdd
#   1. Remove everything related to LVM
#   2. Remove partitions
#
# 2021-12-08
# }}}
# Vars {{{
readonly PROGNAME=$(basename "${0}")
readonly PROGDIR=$(readlink -m $(dirname "${0}"))
readonly ARGS="${*}"
readonly NBARGS="${#}"
[ -z "${DEBUG}" ] && DEBUG=1
## Export DEBUG for sub-script
export DEBUG

# Default values for some vars
#readonly MY_VAR_XY_DEFAULT="666"

## Colors
readonly PURPLE='\033[1;35m'
readonly RED='\033[0;31m'
readonly RESET='\033[0m'
readonly COLOR_DEBUG="${PURPLE}"
# }}}
usage() {                                                       # {{{

	cat <<- EOF
usage: $PROGNAME [-d|-h]

Remove everything related to /dev/sda and /dev/sdb

EXAMPLES :
    - Remove sda and sdb partitions
        ${PROGNAME}

OPTIONS :
    -d,--debug
        Enable debug messages.

    -h,--help
        Print this help message.

	EOF

}
# }}}
debug_message() {                                               # {{{

	local_message="${1}"

	## Print message if DEBUG is enable (=0)
	[ "${DEBUG}" -eq "0" ] && printf '\e[1;35m%-6b\e[m\n' "DEBUG − ${PROGNAME} : ${local_message}"

	return 0
}
# }}}
error_message() {                                               # {{{

	local_error_message="${1}"
	local_error_code="${2}"

	## Print message if DEBUG is enable (=0)
	[ "${DEBUG}" -eq "0" ] && printf '%b\n' "ERROR − ${PROGNAME} : ${RED}${local_error_message}${RESET}"

	exit "${local_error_code:=66}"
}
# }}}
install_dependencies() {                                        # {{{

	## Update APT repositories {{{
	## OR exit
	debug_message "install_dependencies − \
Update repositories…"
	apt update > /dev/null \
		|| exit 1
	## }}}

	## Install dependencies {{{
	## OR exit
	debug_message "install_dependencies − \
Install some packages…"
	apt install -y coreutils e2fsprogs gawk lvm2 thin-provisioning-tools parted util-linux > /dev/null \
		|| exit 2
	## }}}

}
# }}}
is_vg_available() {                                             # {{{

	## Return False by default
	return_is_vg_available="1"

	## If at least 1 VG is available
	if [ `vgs --noheadings | wc --line` -gt 0 ]; then
		debug_message "is_vg_available − \
At least one Volume Group is ${RED}available${COLOR_DEBUG}."
		return_is_vg_available="0"
	else
		debug_message "is_vg_available − \
${RED}No${COLOR_DEBUG} Volume Group available on this host."
		return_is_vg_available="1"
	fi

	return "${return_is_vg_available}"

}
# }}}
remove_vg() {                                                   # {{{

	local_vg_name="${1}"

	## Return False by default
	return_remove_vg="1"

	## If the Volume Group is successfully removed
	if vgremove "${local_vg_name}" ; then
		debug_message "remove_vg − \
${local_vg_name} Volume Group was successfully ${RED}removed${COLOR_DEBUG}."
		return_remove_vg="0"
	else
		debug_message "remove_vg − \
Error with ${RED}vgremove${COLOR_DEBUG} command."
		return_remove_vg="1"
	fi

	return "${return_remove_vg}"

}
# }}}
is_pv_available() {                                             # {{{

	## Return False by default
	return_is_pv_available="1"

	## If at least 1 PV is available
	if [ `pvs --noheadings | wc --line` -gt 0 ]; then
		debug_message "is_pv_available − \
At least one Physical Volume is ${RED}available${COLOR_DEBUG}."
		return_is_pv_available="0"
	else
		debug_message "is_pv_available − \
${RED}No${COLOR_DEBUG} Physical Volume available on this host."
		return_is_pv_available="1"
	fi

	return "${return_is_pv_available}"

}
# }}}
remove_pv() {                                                   # {{{

	local_pv_path="${1}"

	## Return False by default
	return_remove_pv="1"

	## If the Physical Volume is successfully removed
	if pvremove "${local_pv_path}" ; then
		debug_message "remove_pv − \
${local_pv_path} was successfully ${RED}removed${COLOR_DEBUG}."
		return_remove_pv="0"
	else
		debug_message "remove_pv − \
Error with ${RED}pvremove${COLOR_DEBUG} command."
		return_remove_pv="1"
	fi

	return "${return_remove_pv}"

}
# }}}

main() {                                                        # {{{

	## Install dependencies
	install_dependencies

	## If a Volume Group is available {{{
	## AND Disable all Volume Group (and related Logical Volumes)
	while is_vg_available; do
		### Get first Volume Group name
		vg_name=$(vgs --noheadings | awk '{ print $1; exit }')

		### Ensure to disable all Volume Group
		debug_message "main − \
Disable all Volume Group and related Logical Volumes."
		vgchange --quiet --activate n

		### Try to remove the Volume Group
		### OR exit
		remove_vg "${vg_name}" \
			|| error_message "Error while trying to remove ${vg_name} Volume Group. Use --debug option for more informations." 3
	done
	## }}}

	## If a Physical Volume is available {{{
	while is_pv_available; do
		### Get first Physical Volume path
		pv_path=$(pvs --noheadings | awk '{ print $1; exit }')

		debug_message "main − \
Try to manage ${RED}${pv_path}${COLOR_DEBUG} Physical Volume."

		### Try to remove the Physical Volume
		### OR exit
		remove_pv "${pv_path}" \
			|| error_message "Error while trying to remove ${pv_path} Physical Volume. Use --debug option for more informations." 4
	done
	## }}}

	## If a Physical Volume is available {{{
	while is_pv_available; do
		### Get first Physical Volume path
		pv_path=$(pvs --noheadings | awk '{ print $1; exit }')

		debug_message "main − \
Try to manage ${RED}${pv_path}${COLOR_DEBUG} Physical Volume."

		### Try to remove the Physical Volume
		### OR exit
		remove_pv "${pv_path}" \
			|| error_message "Error while trying to remove ${pv_path} Physical Volume. Use --debug option for more informations." 4
	done
	## }}}

	# Remove all old partitions for sda and sdb {{{
	for hdd in /dev/sda /dev/sdb; do
		## Start partition number to 32
		part_number="32"
		while [ "${part_number}" -gt 0 ]
		do
			### If partition exists {{{
			if [ -b "${hdd}${part_number}" ]; then
				debug_message "main − \
Try to remove ${hdd}${part_number} partition."

				parted "${hdd}" rm "${part_number}" \
					|| error_message "Can't remove ${hdd}${part_number} partition." 5
			fi
			### }}}

			### Decrease partition number
			part_number=$(($part_number-1))
		done
	done
	## }}}

	printf '%b\n' "All disks were successfully cleaned. \
You can reboot the system to update mtab."

}
# }}}

# Manage arguments                                                # {{{
# This code can't be in a function due to argument management

if [ ! "${NBARGS}" -eq "0" ]; then

	manage_arg="0"

	## If the first argument is not an option
	if ! printf -- '%s' "${1}" | grep -q -E -- "^-+";
	then
		## Print help message and exit
		printf '%b\n' "${RED}Invalid option: ${1}${RESET}"
		printf '%b\n' "---"
		usage

		exit 1
	fi

	# Parse all options (start with a "-") one by one
	while printf -- '%s' "${1}" | grep -q -E -- "^-+"; do

	case "${1}" in
		-d|--debug )                          ## debug
			DEBUG=0
			;;
		-h|--help )                           ## help
			usage
			## Exit after help informations
			exit 0
			;;
		#-v|--var )                            ## Define var with given arg
			### Move to the next argument
			#shift
			### Define var
			#readonly my_var_xy="${1}"
			#;;
		* )                                   ## unknow option
			printf '%b\n' "${RED}Invalid option: ${1}${RESET}"
			printf '%b\n' "---"
			usage
			exit 1
			;;
	esac

	debug_message "Arguments management − \
${RED}${1}${COLOR_DEBUG} option managed."

	## Move to the next argument
	shift
	manage_arg=$((manage_arg+1))

	done

	debug_message "Arguments management − \
${RED}${manage_arg}${COLOR_DEBUG} argument(s) successfully managed."
else
	debug_message "Arguments management − \
No arguments/options to manage."
fi

# }}}

main

exit 0