#!/bin/bash

## bash library for formatusb

##arguments format, label, device

expected_diskseq=$5  # optional for legacy direct callers
partnum=""

device="$1"
format="$2"
label="$3"
part="$4"  #can be part, defaults, gpt, or msdos

case "${part,,}" in
     part)     part=part     ;;
     gpt)      part=gpt      ;;
     msdos)    part=msdos    ;;
     defaults) part=defaults ;;
     # Fail closed: an unrecognised mode must not silently fall through to
     # "defaults" (whole-disk repartitioning) on a destructive privileged helper.
        *) echo "Invalid partition mode: $part" >&2; exit 2 ;;
esac

# SECURITY: $device is interpolated (often unquoted) into many root commands
# below (df/dd/parted/blkid/sfdisk). This helper is directly pkexec-invocable,
# so GUI-side checks are bypassable — validate the device name here. A real
# block-device name (sdb1, mmcblk0p1, nvme0n1p1) is alphanumeric only; this
# rejects any shell metacharacter / path separator.
if [[ ! "$device" =~ ^[A-Za-z0-9]+$ ]]; then
    echo "Invalid device name: $device" >&2
    exit 2
fi

# Must be a real block device (the helper is directly pkexec-invocable, so this
# is not guaranteed by the GUI device list).
if [ ! -b "/dev/$device" ]; then
    echo "Not a block device: /dev/$device" >&2
    exit 2
fi

expected_type=disk
[[ "$part" == part ]] && expected_type=part
target_type=$(lsblk -ndo TYPE "/dev/$device") || exit 2
if [[ "$target_type" != "$expected_type" ]]; then
    echo "Mode $part requires a $expected_type device, got $target_type for /dev/$device" >&2
    exit 2
fi

# Compare the complete dependency chains, including every member of a RAID
# or multi-disk LVM volume. KNAME identifies the same node through any alias.
target_ancestors=$(lsblk --inverse --raw --noheadings --output KNAME "/dev/$device") || exit 3
for _mnt in / /boot /boot/efi /live/boot-dev /live/to-ram /lib/live/mount/medium /run/live/medium; do
    _src=$(findmnt -fn -o SOURCE "$_mnt" 2>/dev/null) || continue
    _src=${_src%%[*}              # strip btrfs subvol suffix, e.g. /dev/sda2[/@]
    [ -b "$_src" ] || continue
    protected_ancestors=$(lsblk --inverse --raw --noheadings --output KNAME "$_src") || exit 3
    if grep -Fxq -f <(printf '%s\n' "$target_ancestors") <<< "$protected_ancestors"; then
        echo "Refusing to format /dev/$device: it backs the running system or live medium" >&2
        exit 3
    fi
done

# Reject unknown filesystem types up front. Otherwise format_partitions()
# treats an unknown format as a no-op "success" (its *) branch returns 0 and
# checkerrorcode reports OK) -- but for a non-"part" mode the disk has already
# been wiped/repartitioned by then, so fail closed before any disk writes.
case "$format" in
    vfat|ext4|ntfs|exfat) ;;
    *) echo "Invalid format: $format" >&2; exit 2 ;;
esac

# Validate the filesystem label server-side. This helper is directly
# pkexec-invocable, so the GUI's validate_name() check is bypassable and the
# label (used below as a parted partition name and as the *label tool argument)
# must be re-checked here. An empty label is allowed (means "no label");
# otherwise enforce the same contract the GUI does -- the character set
# [A-Za-z0-9_.-] plus the per-filesystem length limit -- so a label the GUI
# would reject can't reach mkpart/*label. The set excludes every shell
# metacharacter and path separator.
if [ -n "$label" ]; then
    case "$format" in
        ext4) label_max=16 ;;
        ntfs) label_max=32 ;;
        *)    label_max=11 ;;   # vfat, exfat
    esac
    if [ "${#label}" -gt "$label_max" ] || [[ ! "$label" =~ ^[A-Za-z0-9_.-]+$ ]]; then
        echo "Invalid label: $label" >&2
        exit 2
    fi
fi

echo device is $device format is $format
echo label is $label

check_required_tools()
{
    local tool label_tool
    local -a required=(lsblk findmnt grep umount mkdir udevadm rm partprobe sleep
                       blkid sfdisk cp mv id logname)
    if [[ "$part" != part ]]; then
        required+=(parted dd sed)
    fi
    case "$format" in
        vfat)  required+=(mkfs.fat); label_tool=fatlabel ;;
        ntfs)  required+=(mkfs.ntfs); label_tool=ntfslabel ;;
        exfat) required+=(mkfs.exfat); label_tool=exfatlabel ;;
        ext4)  required+=(mkfs.ext4 mount getent cut mktemp chown chmod rmdir); label_tool=e2label ;;
    esac
    [[ -n "$label" ]] && required+=("$label_tool")
    for tool in "${required[@]}"; do
        if ! command -v "$tool" >/dev/null; then
            echo "Missing required tool: $tool" >&2
            exit 1
        fi
    done
}

check_disk_identity()
{
    [[ -n "$expected_diskseq" ]] || return 0
    local path="/sys/class/block/$device" actual
    if [[ -f "$path/partition" ]]; then
        path="$path/.."
    fi
    if [[ "$expected_diskseq" == "-" && -d "$path" && ! -e "$path/diskseq" ]]; then
        return 0
    fi
    if [[ "$expected_diskseq" =~ ^[0-9]+$ ]] && read -r actual < "$path/diskseq" && [[ "$actual" == "$expected_diskseq" ]]; then
        return 0
    fi
    echo "Device /dev/$device changed. Refresh the device list and select it again." >&2
    exit 3
}

unmount_partitions()
{
	local nodes node mountpoint remaining
	nodes=$(lsblk -nrpo KNAME,MOUNTPOINT "/dev/$device") || exit 1
	while read -r node mountpoint; do
		[ -n "$mountpoint" ] || continue
		umount --all-targets -- "$node"
		checkerrorcode "unmount $node"
	done <<< "$nodes"

	remaining=$(lsblk -nro MOUNTPOINT "/dev/$device") || exit 1
	if [[ "$remaining" =~ [^[:space:]] ]]; then
		echo "Device /dev/$device still has mounted filesystems" >&2
		exit 1
	fi
}

# Re-read the partition table once udev has finished processing events, and
# retry a few times: right after a wipe/mklabel, udev or automount may still
# hold the old partitions briefly, making partprobe fail with EBUSY.
refresh_partitions()
{
	local dev="$1" i
	udevadm settle 2>/dev/null
	for i in 1 2 3; do
		if partprobe "$dev"; then
			udevadm settle 2>/dev/null
			return 0
		fi
		sleep 1
	done
	return 1
}

##clear_partitions from live-usb-maker by James Bowlin (BitJam) for antiX
clear_partitions()
{
    local dev=/dev/$device
    local bytes
    bytes=$(parted --script $dev unit B print 2>/dev/null | sed -rn "s/^Disk.*: ([0-9]+)B$/\1/ip")
    local block_size=512
    local pt_size=$((17 * 1024))
    local pt_cnt=$((pt_size / block_size))

    local total_blocks=$((bytes / $block_size))
    #echo -e "Total bytes: $bytes\nTotal blocks: $total_blocks"

    check_disk_identity
    # Clear out previous primary partition table
    dd if=/dev/zero of=$dev bs=$block_size count=$pt_cnt

    checkerrorcode "primary partition table clear"

    sleep 1

    # Clear out sneaky iso-hybrid partition table
    dd if=/dev/zero of=$dev bs=$block_size count=$pt_cnt seek=64

    checkerrorcode "iso-hybrid partition table clear"

	sleep 1

    [ -n "$bytes" ] || return
    local offset=$((total_blocks - $pt_cnt))

    # Clear out secondary gpt partition table
    dd conv=notrunc if=/dev/zero of=$dev bs=$block_size count=$pt_cnt seek=$offset


    checkerrorcode "secondary partition table clear"

    # Tell kernel the partition table has changed
    echo "refresh partitions info $dev"
    refresh_partitions "$dev"
    checkerrorcode "refresh partitions info"
}

create_partition()
{
	local dev=/dev/$device
	local option
	unmount_partitions
	sleep 1

	local bytes
	bytes=$(lsblk --bytes --nodeps --noheadings --output SIZE $dev 2>/dev/null)
	bytes=$((bytes / 1))
	local mbrlimit=$((2000 * 1024 * 1024 * 1024)) # about 2TB - devices over this size are made to gpt
	local parttabletype

    echo "bytes $bytes limit $mbrlimit"

	if [ "$part" = "defaults" ]; then
		if (($bytes <= $mbrlimit)) ; then # the <= prevents a race condition
			parttabletype="msdos"
			option="primary"
			echo "making new dos partition table"
			sleep 1
		fi

		if (($bytes > $mbrlimit)) ; then
			parttabletype="gpt"
			echo "making new gpt partition table"
			sleep 1
		fi
	fi

	if [ "$part" = "gpt" ]; then
		parttabletype="gpt"
		echo "making new gpt partition table"
		sleep 1
	fi

	if [ "$part" = "msdos" ]; then
		parttabletype="msdos"
		option="primary"
		echo "making new msdos partition table"
		sleep 1
	fi

	# GPT mkpart always takes a NAME argument: use the filesystem label, or an
	# explicit empty name ('""' in parted's syntax) when no label is set.
	# Otherwise parted reads "1" as the name and fails for lack of an end.
	if [ "$parttabletype" = "gpt" ]; then
		option="${label:-\"\"}"
	fi

	udevadm settle 2>/dev/null
	parted -s "$dev" mklabel "$parttabletype"
	checkerrorcode "making new partition table"

	refresh_partitions "$dev"
	checkerrorcode "refresh partitions info"

	# Create partition. $option is "primary" (msdos), the label (gpt), or '""' (gpt, no label).
	parted -s -a optimal "$dev" mkpart "$option" 1MiB 100%
	checkerrorcode "create new partition"

	refresh_partitions "$dev"
	checkerrorcode "refresh partitions info"
}


makeusb(){
live-usb-maker gui --format="$format" --color=off -t "$device"
}

labelusb(){

if [ -z "$label" ]; then
	return
fi

#ensure the partition is unmounted before labeling; skip when it isn't mounted
#so a freshly-formatted (unmounted) partition doesn't trip checkerrorcode
if findmnt -S "/dev/$device$partnum" &>/dev/null; then
    umount -q /dev/"$device$partnum" 2>/dev/null
    checkerrorcode "unmount partitions"
fi



case $format in

	vfat) fatlabel /dev/"$device$partnum" "$label"  ;;

	ext4)  e2label /dev/"$device$partnum" "$label"  ;;

	ntfs)  ntfslabel /dev/"$device$partnum" "$label"  ;;

	exfat) exfatlabel /dev/"$device$partnum" "$label"  ;;

	*)	echo "unknown format, exiting"  ;;

esac


checkerrorcode "label partition"
}

# Strip the partition suffix from a composite device+partition string to obtain
# the parent block device ("refreshdevice") and the bare partition number
# ("partition_to_mark").  Handles the three device-naming conventions found in
# the kernel: sdX (sdX1), mmcblkX (mmcblkXp1), nvmeXnY (nvmeXnYp1).
resolve_partition_ref(){
	local dev="$1"
	if [[ "$dev" == *"mmc"* ]] || [[ "$dev" == *"nvme"* ]]; then
		refreshdevice="${dev%p*}"
		filter="${refreshdevice}p"
		partition_to_mark="${partition_dev#$filter}"
	elif [[ "$dev" == *"sd"* ]]; then
		refreshdevice="${dev//[0-9]/}"
		partition_to_mark="${partition_dev#$refreshdevice}"
	fi
}

partitionrefresh(){

	##need device not partition

	local refreshdevice partition_to_mark filter partition_dev mark

	partition_dev="$device$partnum"

	resolve_partition_ref "$device"

echo "Device $device"
echo "Refresh Partitions $refreshdevice"
echo "partition to mark $partition_to_mark"

    local table
    table=$(blkid -s PTTYPE -o value "/dev/$refreshdevice")
    checkerrorcode "Reading partition table type"
    case "$table" in
        gpt)
            if [[ "$format" == ext4 ]]; then
                mark="0FC63DAF-8483-4772-8E79-3D69D8477DE4"
            else
                mark="EBD0A0A2-B9E5-4433-87C0-68B6B72699C7"
            fi
            ;;
        dos)
            case "$format" in
                ext4) mark=83 ;;
                vfat) mark=c ;;
                exfat | ntfs) mark=7 ;;
            esac
            ;;
        *)
            if [[ "$format" != ext4 ]]; then
                echo "Unrecognized partition table on /dev/$refreshdevice" >&2
                exit 1
            fi
            # No ext4 type mapping is defined here for other partition tables.
            ;;
    esac
    if [[ -n "$mark" ]]; then
        sfdisk --part-type "/dev/$refreshdevice" "$partition_to_mark" "$mark"
        checkerrorcode "Setting Partition Type"
    fi

partprobe "/dev/$refreshdevice"

checkerrorcode "refresh partition info"

}

cleanuplog(){
	local dest="/var/log/formatusb.log" old="/var/log/formatusb.log.old" uid dir src
	# Where the GUI wrote its log: a user session logs to its private runtime
	# dir (/run/user/<uid>); a root run logs to /run. Both are non-world-writable.
	# World-writable /tmp is deliberately NOT searched as root: even with symlinks
	# rejected, its content and size would be attacker-controllable. The caller's
	# uid comes from pkexec/sudo/login.
	if [[ "$PKEXEC_UID" =~ ^[0-9]+$ ]]; then
		uid="$PKEXEC_UID"
	elif [[ "$SUDO_UID" =~ ^[0-9]+$ ]]; then
		uid="$SUDO_UID"
	else
		uid=$(id -u "$(logname)" 2>/dev/null)
	fi
	local -a logdirs=()
	[[ "$uid" =~ ^[0-9]+$ && "$uid" -ne 0 ]] && logdirs+=("/run/user/${uid}")
	logdirs+=("/run")
	for dir in "${logdirs[@]}"; do
		[[ -d "$dir" ]] || continue
		src="${dir}/formatusb.log"
		# Only act on a real regular file, never a symlink, so the source
		# cannot be redirected at a root-owned file.
		[[ -f "$src" && ! -L "$src" ]] || continue
		# Rotate the destination, never following a symlink left there.
		if [[ -L "$dest" ]]; then
			rm -f -- "$dest"
		elif [[ -f "$dest" ]]; then
			mv -- "$dest" "$old"
		fi
		# -P: if the source is swapped for a symlink in a race, copy the link
		# itself rather than dereferencing it to another file.
		cp -P -- "$src" "$dest"
		return 0
	done
}

partnumber()
{
	#ensure some partnums when working on devices

if [ "$part" != "part" ]; then

	partnum="1"

	#if device is mmc, then partnum=p1

	if [[ "$device" == *"mmc"* ]]; then
		partnum="p1"
	fi

	#if device is nvme, then partnum=p1
	if [[ "$device" == *"nvme"* ]]; then
		partnum="p1"
	fi
fi
}

format_partitions(){

	echo "formatting partitions $device$partnum"

	#ensure device is unmounted
	unmount_partitions

	check_disk_identity
	case $format in

	vfat) mkfs.fat -F 32 /dev/"$device$partnum"  ;;

	ext4)  mkfs.ext4 -F /dev/"$device$partnum"
		   checkerrorcode "format ext4 partition"
		   change_ownership;;

	ntfs)  mkfs.ntfs -Q /dev/"$device$partnum"  ;;

	exfat) mkfs.exfat /dev/"$device$partnum" ;;

	*)	echo "unknown format, exiting" ;;



esac

checkerrorcode "format partition"

}

disable_automount()
{
mkdir -p /run/udev/rules.d

checkerrorcode "hide disk from udev"
echo 'SUBSYSTEM=="block", ENV{UDISKS_IGNORE}="1"' > /run/udev/rules.d/91-mx-udisks-inhibit.rules
AUTOMOUNT_DISABLED=1   # tells the cleanup trap to re-enable automount on any exit
udevadm control --reload
udevadm trigger --subsystem-match=block

}

enable_automount()
{
rm -f /run/udev/rules.d/91-mx-udisks-inhibit.rules

checkerrorcode "make disk visible to udev"
AUTOMOUNT_DISABLED=""   # disarm the cleanup trap's re-enable once done normally
udevadm control --reload
udevadm trigger --subsystem-match=block
}

change_ownership()
{
	local USERNAME mountpoint
	# Resolve the calling user from the polkit-provided uid (fall back to
	# logname) rather than trusting the controlling terminal alone.
	if [[ "$PKEXEC_UID" =~ ^[0-9]+$ ]]; then
		USERNAME=$(getent passwd "$PKEXEC_UID" | cut -d: -f1)
	fi
	[[ -z "$USERNAME" ]] && USERNAME=$(/usr/bin/logname)
	[[ -z "$USERNAME" ]] && return

	# Use a fresh, root-owned, random mount point (mode 0700) instead of a
	# predictable world-writable /tmp path an attacker could pre-create/symlink.
	mountpoint=$(mktemp -d /run/formatusb-mnt.XXXXXX) || return
	# Register the temp mount for the global cleanup trap so it is always torn
	# down, even if a step below fails and exits (checkerrorcode exits on error).
	TEMP_MOUNT="$mountpoint"

	# Check the mount immediately: if it fails, chown/chmod would silently act
	# on the empty temp dir and the new filesystem would never be owned by the
	# user. checkerrorcode aborts here on failure (and the trap cleans up).
	mount -t ext4 /dev/"$device$partnum" "$mountpoint"
	checkerrorcode "Mounting new partition to set ownership"

	chown "$USERNAME":users "$mountpoint"
	checkerrorcode "Changing owner of partition to $USERNAME:users"

	chmod -R 775 "$mountpoint"
	checkerrorcode "Changing permissions of partition to $USERNAME:users"

	# Verify the unmount succeeded before reporting success, so a failed umount
	# is not logged OK while leaving the filesystem mounted.
	umount -q "$mountpoint"
	checkerrorcode "Unmounting temporary mount point"
	rmdir "$mountpoint"
	checkerrorcode "Removing temporary mount point"
	TEMP_MOUNT=""
}

checkerrorcode()
{
	retval=$?
	local msg="$1"
	#echo "retval is $retval"
	if [ ! $retval = 0 ]; then
		echo "$msg" "ERROR"
		exit "$retval"
	else
		echo "$msg" "OK"
	fi
}

# Always-run cleanup: re-enable automount and tear down the temp mount point on
# ANY exit, including checkerrorcode's mid-run exit. Preserves the exit status.
_cleanup()
{
	local rc=$?
	if [ -n "$TEMP_MOUNT" ]; then
		umount -q "$TEMP_MOUNT" 2>/dev/null
		rmdir "$TEMP_MOUNT" 2>/dev/null
		TEMP_MOUNT=""
	fi
	if [ -n "$AUTOMOUNT_DISABLED" ]; then
		rm -f /run/udev/rules.d/91-mx-udisks-inhibit.rules
		udevadm control --reload 2>/dev/null
		udevadm trigger --subsystem-match=block 2>/dev/null
		AUTOMOUNT_DISABLED=""
	fi
	exit "$rc"
}

main(){

trap _cleanup EXIT

check_required_tools
check_disk_identity
unmount_partitions
disable_automount

if [ "$part" = "part" ]; then
	format_partitions
else
	clear_partitions
	sleep 1
	create_partition
	sleep 1
	partnumber
	format_partitions
	sleep 1
fi
	labelusb
	sleep 1
	partitionrefresh
	cleanuplog
	enable_automount
}

main
