#!/bin/bash
# Author: Steven Shiau <steven _at_ clonezilla org>
# License: GPL
#
# To solve the small partition image restored to larger partition problem.
# Improved by Google's Gemini for safety and reliability.

DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/usr/share/drbl}"

. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions
. /etc/drbl/drbl-ocs.conf
. $DRBL_SCRIPT_PATH/sbin/ocs-functions

# Settings
run_ntfsfix="no"
batch_mode="no"
dry_run="no"

#
export LC_ALL=C

# Track temporary mount directory specifically created by this script
current_tmp_mnt=""

USAGE() {
   echo "Usage: [OPTION] DEVICE"
   echo "DEVICE name can be with or without /dev/, e.g., /dev/sda1 or sda1."
   echo
   echo "OPTION:"
   echo "-b, --batch    Run program in batch mode, i.e. without any prompt or wait to press enter."
   echo "-d, --dry-run  Perform trial run, i.e., do not actually make changes to the filesystem."
   echo "-n, --ntfsfix  Run ntfsfix before resizing a NTFS partition."
   echo "-h, --help     Show this help and exit."
   echo
   echo "Example: $0 /dev/sdc1"
}

cleanup() {
  # If a temporary mount directory was created and is currently mounted, unmount it.
  if [ -n "$current_tmp_mnt" ] && [ -d "$current_tmp_mnt" ]; then
     if findmnt -n -o TARGET "$current_tmp_mnt" >/dev/null 2>&1; then
         echo "Interrupted! Unmounting $partition from $current_tmp_mnt..."
         umount "$current_tmp_mnt" 2>/dev/null || umount -l "$current_tmp_mnt" 2>/dev/null
     fi
     rmdir "$current_tmp_mnt" 2>/dev/null || rm -rf "$current_tmp_mnt" 2>/dev/null
     current_tmp_mnt=""
  fi
}
trap cleanup EXIT INT TERM

# Handles the logic for FS types that must be mounted to be resized (XFS, JFS, BTRFS, NILFS2)
resize_via_mount() {
  local fs_type="$1"
  local resize_cmd_template="$2" # Use __MNT__ as placeholder for mountpoint
  local mount_opts="$3"          # Optional mount options (e.g. "nouuid" for xfs)
  local tool_name="${resize_cmd_template%% *}" # Get the first word (command name)

  if ! type "$tool_name" &>/dev/null; then
      echo "$tool_name: command not found! Skip growing this partition ${partition}"
      return 1
  fi

  if [ "$dry_run" = "yes" ]; then
      echo "[Dry-run] Would mount -t $fs_type ${mount_opts:+-o $mount_opts }${partition} to temporary directory"
      echo "[Dry-run] Would execute: ${resize_cmd_template//__MNT__/<temporary-mountpoint>}"
      echo "[Dry-run] Would unmount ${partition} and remove temporary mount directory"
      return 0
  fi

  local TMP_MNT
  TMP_MNT="$(mktemp -d /tmp/ocs-resize-${fs_type}mnt.XXXXXX)" || {
      echo "Failed to create temporary mount directory!"
      exit 1
  }
  current_tmp_mnt="$TMP_MNT"
  
  # Try to mount. If mount_opts is provided, try with mount_opts first, then fallback without.
  local rc=1
  if [ -n "$mount_opts" ]; then
      mount -t "$fs_type" -o "$mount_opts" "$partition" "$TMP_MNT" 2>/dev/null
      rc=$?
  fi
  if [ "$rc" -ne 0 ]; then
      mount -t "$fs_type" "$partition" "$TMP_MNT"
      rc=$?
  fi
  
  if [ "$rc" -eq 0 ]; then
    echo "Running resize operation for $fs_type on $partition..."
    
    # Replace __MNT__ with the actual temp path and execute
    local final_cmd="${resize_cmd_template//__MNT__/$TMP_MNT}"
    echo "Executing: $final_cmd"
    local resize_rc=0
    eval "$final_cmd" || resize_rc=$?
    
    sync
    sleep 1
    umount "$TMP_MNT" 2>/dev/null || umount -l "$TMP_MNT" 2>/dev/null
    [ -d "$TMP_MNT" ] && rmdir "$TMP_MNT" 2>/dev/null
    current_tmp_mnt=""

    if [ "$resize_rc" -ne 0 ]; then
      echo "Resize operation failed for $fs_type on $partition (exit code $resize_rc)!"
      return $resize_rc
    fi
    return 0
  else
    current_tmp_mnt=""
    [ -d "$TMP_MNT" ] && rmdir "$TMP_MNT" 2>/dev/null
    echo "Failed to mount $fs_type partition $partition!"
    echo "Without mounting, we cannot increase the filesystem size to fit partition size!"
    echo "Program terminated!"
    exit 1
  fi
}

# Parse command-line options
while [ $# -gt 0 ]; do
  case "$1" in
    -b|--batch)
            batch_mode="yes"
            shift;;
    -d|--dry-run)
            dry_run="yes"
            shift;;
    -n|--ntfsfix)
            run_ntfsfix="yes"
            shift;;
    -h|--help)
            USAGE
            exit 0;;
    -*)     echo "${0}: ${1}: invalid option" >&2
            USAGE >& 2
            exit 2 ;;
    *)      break ;;
  esac
done

[ $# -ne 1 ] && USAGE && exit 1
# No matter the input is like /dev/sda or sda, format it as /dev/sda
partition="$(format_dev_name_with_leading_dev $1)"

###################
### Main script ###
###################
check_if_root
ask_and_load_lang_set
#
if [ ! -b "$partition" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  echo "Block device \"$partition\" not found!"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo "$msg_program_stop!"
  my_ocs_exit 1
fi

if [ "$(blockdev --getro "$partition" 2>/dev/null)" = "1" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "Block device \"$partition\" is in read-only mode! Skip resizing that."
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  exit 1
fi

if findmnt --source "$partition" >/dev/null; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
  echo "Partition $partition is already mounted! You must unmount it first! Program terminated!"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  exit 1
fi

# Check partition, if no such partition exist, exit, otherwise "parted $partition p" will hang
part_fs="$(ocs-get-dev-info "$partition" filesystem)"
if [ -z "$part_fs" ]; then
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "Unknown or unsupported partition ($partition) found! Skip this partition ${partition}."
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  exit 1
fi

case "$part_fs" in
   reiserfs)
              if ! command -v resize_reiserfs &> /dev/null; then
                 echo "resize_reiserfs: command not found! Skip resizing this partition ${partition}"
                 exit 1
              fi
              resize_reiserfs_opt=""
              [ "$batch_mode" = "yes" ] && resize_reiserfs_opt="-f"
              if [ "$dry_run" = "yes" ]; then
                 echo "[Dry-run] Would execute: resize_reiserfs $resize_reiserfs_opt ${partition}"
              else
                 echo "resize_reiserfs $resize_reiserfs_opt ${partition}"
                 resize_reiserfs $resize_reiserfs_opt "${partition}"
              fi
              ;;
   vfat|fat12|fat16|fat32)
              if ! command -v fatresize &> /dev/null; then
                 [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
                 echo "Program fatresize not found! Skip this partition ${partition}"
                 [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
                 exit 1
              fi
              fat_fs_size="$(LC_ALL=C lsblk -b -n -d -o size "${partition}" 2>/dev/null)"
              if [ -z "$fat_fs_size" ] || ! [[ "$fat_fs_size" =~ ^[0-9]+$ ]] || [ "$fat_fs_size" -le 1 ]; then
                 fat_fs_size="$(LC_ALL=C ocs-get-dev-info "${partition}" size 2>/dev/null)"
              fi
              if [ -z "$fat_fs_size" ] || ! [[ "$fat_fs_size" =~ ^[0-9]+$ ]] || [ "$fat_fs_size" -le 1 ]; then
                 [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
                 echo "Unable to determine partition size for ${partition}! Skip resizing."
                 [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
                 exit 1
              fi
              fatresize_opt=""
              [ "$batch_mode" = "yes" ] && fatresize_opt="-f"
              target_fat_size=$((fat_fs_size - 1))
              # A workaround to avoid fatresize 1.1.0 bug. We do not extend it to the boundary.
              # Just try to resize it smaller.
              # If we run fatresize with "-s max", it will complain:
              # .Error: Can't have overlapping partitions.
              # Ref: https://github.com/ya-mouse/fatresize/issues/18
              #      https://gitlab.tails.boum.org/tails/tails/-/issues/18699
              if [ "$dry_run" = "yes" ]; then
                 echo "[Dry-run] Would execute: fatresize $fatresize_opt -p --verbose -s $target_fat_size ${partition}"
              else
                 echo "fatresize $fatresize_opt -p --verbose -s $target_fat_size ${partition}"
                 fatresize $fatresize_opt -p --verbose -s $target_fat_size "${partition}"
              fi
              ;;
   ext2|ext3|ext4|ext4dev)
              if ! command -v e2fsck &> /dev/null || ! command -v resize2fs &> /dev/null; then
                 echo "e2fsck or resize2fs: command not found! Skip resizing this partition ${partition}"
                 exit 1
              fi
              resize2fs_opt=""
              [ "$batch_mode" = "yes" ] && resize2fs_opt="-f"
              if [ "$dry_run" = "yes" ]; then
                 echo "[Dry-run] Would execute: e2fsck -f -y ${partition}; resize2fs -p $resize2fs_opt ${partition}"
              else
                 echo "e2fsck -f -y ${partition}; resize2fs -p $resize2fs_opt ${partition}"
                 e2fsck -f -y "${partition}"
                 e2fsck_rc=$?
                 # e2fsck: 0 = no error, 1 = errors corrected, 2 = errors corrected (reboot needed)
                 # 4 or higher indicates uncorrected errors or operational error
                 if [ "$e2fsck_rc" -ge 4 ]; then
                    [ "$BOOTUP" = "color" ] && $SETCOLOR_FAILURE
                    echo "e2fsck reported uncorrected errors (exit code $e2fsck_rc) on ${partition}! Skip resizing."
                    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
                    exit $e2fsck_rc
                 fi
                 resize2fs -p $resize2fs_opt "${partition}"
              fi
              ;;
   ntfs)
              if ! command -v ntfsresize &> /dev/null; then
                 echo "ntfsresize: command not found! Skip resizing this partition ${partition}"
                 exit 1
              fi
              ntfsresize_opt=""
              [ "$batch_mode" = "yes" ] && ntfsresize_opt="-f -f"
              if [ "$dry_run" = "yes" ]; then
                 [ "$run_ntfsfix" = "yes" ] && echo "[Dry-run] Would execute: ntfsfix ${partition}"
                 echo "[Dry-run] Would execute: ntfsresize $ntfsresize_opt ${partition}"
              else
                 if [ "$run_ntfsfix" = "yes" ]; then
                    if command -v ntfsfix &> /dev/null; then
                       ntfsfix "${partition}"
                    else
                       echo "ntfsfix: command not found! Skipping ntfsfix."
                    fi
                 fi
                 echo "ntfsresize $ntfsresize_opt ${partition}"
                 ntfsresize $ntfsresize_opt "${partition}"
              fi
              ;;
   xfs)
              # Mount with nouuid to handle cloned disks with identical UUIDs, then run xfs_growfs
              resize_via_mount "xfs" "xfs_growfs __MNT__" "nouuid"
              ;;
   jfs)
              # Ref: http://jfs.sourceforge.net/project/pub/faq.txt
              # Mount, then remount with resize option
              resize_via_mount "jfs" "mount -o remount,resize __MNT__"
              ;;
   btrfs)
              # Mount, then run btrfs filesystem resize on the mountpoint
              resize_via_mount "btrfs" "btrfs filesystem resize max __MNT__"
              ;;
   nilfs2)
              # Mount, then run nilfs-resize on the DEVICE (requires device to be mounted)
              resize_via_mount "nilfs2" "nilfs-resize -y $partition"
              ;;
   f2fs)
              if ! command -v resize.f2fs &> /dev/null; then
                 echo "resize.f2fs: command not found! Skip resizing this partition ${partition}"
                 exit 1
              fi
              if [ "$dry_run" = "yes" ]; then
                 echo "[Dry-run] Would check f2fs with fsck.f2fs if available"
                 echo "[Dry-run] Would execute: resize.f2fs ${partition}"
              else
                 if command -v fsck.f2fs &> /dev/null; then
                    echo "fsck.f2fs -f -a ${partition}"
                    fsck.f2fs -f -a "${partition}" 2>/dev/null || true
                 fi
                 echo "resize.f2fs ${partition}"
                 resize.f2fs "${partition}"
              fi
              ;;
   swap)
              if ! command -v mkswap &> /dev/null; then
                 echo "mkswap: command not found! Skip resizing swap partition ${partition}"
                 exit 1
              fi
              swap_uuid="$(ocs-get-dev-info "$partition" UUID 2>/dev/null)"
              swap_label="$(ocs-get-dev-info "$partition" LABEL 2>/dev/null)"
              mkswap_opts=""
              [ -n "$swap_uuid" ] && mkswap_opts="$mkswap_opts -U $swap_uuid"
              [ -n "$swap_label" ] && mkswap_opts="$mkswap_opts -L $swap_label"
              if [ "$dry_run" = "yes" ]; then
                 echo "[Dry-run] Would execute: swapoff ${partition} 2>/dev/null"
                 echo "[Dry-run] Would execute: mkswap $mkswap_opts ${partition}"
              else
                 echo "Resizing swap space on ${partition}..."
                 swapoff "${partition}" 2>/dev/null || true
                 echo "mkswap $mkswap_opts ${partition}"
                 mkswap $mkswap_opts "${partition}"
              fi
              ;;
   *)
              [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
              echo "\"$part_fs\" is an unknown or unsupported filesystem... Skip resizing that."
              [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
              exit 1
              ;;
esac
