From dfae3a2fb904224a3676403b2ca26a16fac18005 Mon Sep 17 00:00:00 2001 From: buildplan Date: Wed, 26 Nov 2025 21:33:25 +0000 Subject: [PATCH 01/10] Refactor swap configuration --- du_setup.sh | 233 +++++++++++++++++++++++++++++++++------------------- 1 file changed, 150 insertions(+), 83 deletions(-) diff --git a/du_setup.sh b/du_setup.sh index aa1ed29..76bbfbb 100644 --- a/du_setup.sh +++ b/du_setup.sh @@ -4879,153 +4879,220 @@ test_backup() { } configure_swap() { - if [[ $IS_CONTAINER == true ]]; then + if [[ "$IS_CONTAINER" == true ]]; then print_info "Swap configuration skipped in container." return 0 fi print_section "Swap Configuration" - # Check for existing swap partition + + # Check for existing swap partition entries in fstab for awareness if lsblk -r | grep -q '\[SWAP\]'; then - print_warning "Existing swap partition found. Verify with 'lsblk -f'. Proceed with caution." + print_warning "Existing swap partition found on disk." fi - local existing_swap - existing_swap=$(swapon --show --noheadings | awk '{print $1}' || true) + + # Detect active swap + local existing_swap swap_type + + # --show=NAME,TYPE,SIZE ensures consistent column order + existing_swap=$(swapon --show=NAME,TYPE,SIZE --noheadings --bytes 2>/dev/null | head -n 1 | awk '{print $1}' || true) + if [[ -n "$existing_swap" ]]; then - local current_size - current_size=$(du -h "$existing_swap" | awk '{print $1}') - print_info "Existing swap file found: $existing_swap ($current_size)" - if confirm "Modify existing swap file size?"; then - local SWAP_SIZE - while true; do - read -rp "$(printf '%s' "${CYAN}Enter new swap size (e.g., 2G, 512M) [current: $current_size]: ${NC}")" SWAP_SIZE - SWAP_SIZE=${SWAP_SIZE:-$current_size} - if validate_swap_size "$SWAP_SIZE"; then - break - else - print_error "Invalid size. Use format like '2G' or '512M'." + swap_type=$(swapon --show=NAME,TYPE,SIZE --noheadings | head -n 1 | awk '{print $2}') + + # Get human readable size for display using du (disk usage) + local display_size + display_size=$(du -h "$existing_swap" 2>/dev/null | awk '{print $1}' || echo "Unknown") + + print_info "Existing swap detected: $existing_swap (Type: $swap_type, Size: $display_size)" + + # --- Case 1: Partition detected --- + if [[ "$swap_type" == "partition" ]] || [[ "$existing_swap" =~ ^/dev/ ]]; then + print_warning "The detected swap is a disk partition, which cannot be resized by this script." + + if confirm "Disable this swap partition and create a standard /swapfile instead?" "n"; then + print_info "Disabling swap partition $existing_swap..." + if ! swapoff "$existing_swap"; then + print_error "Failed to disable swap partition. Keeping it active." + return 0 fi - done - local REQUIRED_SPACE - REQUIRED_SPACE=$(convert_to_bytes "$SWAP_SIZE") - local AVAILABLE_SPACE - AVAILABLE_SPACE=$(df -k / | tail -n 1 | awk '{print $4}') - if (( AVAILABLE_SPACE < REQUIRED_SPACE / 1024 )); then - print_error "Insufficient disk space for $SWAP_SIZE swap file. Available: $((AVAILABLE_SPACE / 1024))MB" - exit 1 + + # Comment out the partition in fstab to prevent it mounting on reboot + sed -i "s|^$existing_swap|#$existing_swap|" /etc/fstab + sed -i "s|^UUID=.*swap|#&|" /etc/fstab + print_success "Swap partition disabled and removed from fstab." + + # Clear variable to trigger new file creation below + existing_swap="" + else + print_info "Keeping existing swap partition." + configure_swap_settings + return 0 fi - print_info "Disabling existing swap file..." - swapoff "$existing_swap" || { print_error "Failed to disable swap file."; exit 1; } - print_info "Resizing swap file to $SWAP_SIZE..." - if ! fallocate -l "$SWAP_SIZE" "$existing_swap" || ! chmod 600 "$existing_swap" || ! mkswap "$existing_swap" || ! swapon "$existing_swap"; then - print_error "Failed to resize or enable swap file." - exit 1 - fi - print_success "Swap file resized to $SWAP_SIZE." else - print_info "Keeping existing swap file." + # --- Case 2: Swap File detected --- + if confirm "Modify existing swap file size?"; then + local SWAP_SIZE + while true; do + read -rp "$(printf '%s' "${CYAN}Enter new swap size (e.g., 2G, 512M) [current: $display_size]: ${NC}")" SWAP_SIZE + SWAP_SIZE=${SWAP_SIZE:-$display_size} + if validate_swap_size "$SWAP_SIZE"; then break; else print_error "Invalid size. Use format like '2G' or '512M'."; fi + done + + # Disk space check + local REQUIRED_SPACE AVAILABLE_SPACE + REQUIRED_SPACE=$(convert_to_bytes "$SWAP_SIZE") + AVAILABLE_SPACE=$(df -k / | tail -n 1 | awk '{print $4}') + # Convert available to bytes for comparison (df output is 1K blocks) + if (( (AVAILABLE_SPACE * 1024) < REQUIRED_SPACE )); then + print_error "Insufficient disk space. Required: $SWAP_SIZE, Available: $(numfmt --to=iec $((AVAILABLE_SPACE * 1024)))" + exit 1 + fi + + print_info "Disabling existing swap file..." + swapoff "$existing_swap" || { print_error "Failed to disable swap file."; exit 1; } + + print_info "Resizing swap file to $SWAP_SIZE..." + # Try fallocate first (fast), fallback to dd (compatible) + if ! fallocate -l "$SWAP_SIZE" "$existing_swap" 2>/dev/null; then + print_warning "fallocate failed (filesystem might not support it). Using dd (slower)..." + rm -f "$existing_swap" + # Quoted command substitution for ShellCheck compliance + if ! dd if=/dev/zero of="$existing_swap" bs=1M count="$(convert_to_mb "$SWAP_SIZE")" status=progress; then + print_error "Failed to create swap file with dd." + exit 1 + fi + fi + + if ! chmod 600 "$existing_swap" || ! mkswap "$existing_swap" >/dev/null || ! swapon "$existing_swap"; then + print_error "Failed to configure swap file." + exit 1 + fi + print_success "Swap file resized to $SWAP_SIZE." + else + print_info "Keeping existing swap file." + fi + configure_swap_settings return 0 fi - else + fi + + # --- Case 3: Create New Swap (No swap exists, or partition was disabled above) --- + if [[ -z "$existing_swap" ]]; then if ! confirm "Configure a swap file (recommended for < 4GB RAM)?"; then print_info "Skipping swap configuration." return 0 fi + local SWAP_SIZE while true; do read -rp "$(printf '%s' "${CYAN}Enter swap file size (e.g., 2G, 512M) [2G]: ${NC}")" SWAP_SIZE SWAP_SIZE=${SWAP_SIZE:-2G} - if validate_swap_size "$SWAP_SIZE"; then - break - else - print_error "Invalid size. Use format like '2G' or '512M'." - fi + if validate_swap_size "$SWAP_SIZE"; then break; else print_error "Invalid size. Use format like '2G' or '512M'."; fi done - local REQUIRED_SPACE + + local REQUIRED_SPACE AVAILABLE_SPACE REQUIRED_SPACE=$(convert_to_bytes "$SWAP_SIZE") - local AVAILABLE_SPACE AVAILABLE_SPACE=$(df -k / | tail -n 1 | awk '{print $4}') - if (( AVAILABLE_SPACE < REQUIRED_SPACE / 1024 )); then - print_error "Insufficient disk space for $SWAP_SIZE swap file. Available: $((AVAILABLE_SPACE / 1024))MB" + + if (( (AVAILABLE_SPACE * 1024) < REQUIRED_SPACE )); then + print_error "Insufficient disk space. Required: $SWAP_SIZE, Available: $(numfmt --to=iec $((AVAILABLE_SPACE * 1024)))" exit 1 fi - print_info "Creating $SWAP_SIZE swap file..." - if ! fallocate -l "$SWAP_SIZE" /swapfile || ! chmod 600 /swapfile || ! mkswap /swapfile || ! swapon /swapfile; then - print_error "Failed to create or enable swap file." + + print_info "Creating $SWAP_SIZE swap file at /swapfile..." + if ! fallocate -l "$SWAP_SIZE" /swapfile 2>/dev/null; then + print_warning "fallocate failed. Using dd (slower)..." + # Quoted command substitution for ShellCheck compliance + if ! dd if=/dev/zero of=/swapfile bs=1M count="$(convert_to_mb "$SWAP_SIZE")" status=progress; then + print_error "Failed to create swap file." + rm -f /swapfile || true + exit 1 + fi + fi + + if ! chmod 600 /swapfile || ! mkswap /swapfile >/dev/null || ! swapon /swapfile; then + print_error "Failed to enable swap file." rm -f /swapfile || true exit 1 fi - # Check for existing swap entry in /etc/fstab to prevent duplicates - if grep -q '^/swapfile ' /etc/fstab; then - print_info "Swap entry already exists in /etc/fstab. Skipping." - else + + # Add to fstab if missing + if ! grep -q '^/swapfile ' /etc/fstab; then echo '/swapfile none swap sw 0 0' >> /etc/fstab print_success "Swap entry added to /etc/fstab." + else + print_info "Swap entry already exists in /etc/fstab." fi print_success "Swap file created: $SWAP_SIZE" fi + + configure_swap_settings +} + +# Helper: Apply Sysctl Settings for Swap +configure_swap_settings() { print_info "Configuring swap settings..." local SWAPPINESS=10 local CACHE_PRESSURE=50 + if confirm "Customize swap settings (vm.swappiness and vm.vfs_cache_pressure)?"; then while true; do - read -rp "$(printf '%s' "${CYAN}Enter vm.swappiness (0-100) [default: $SWAPPINESS]: ${NC}")" INPUT_SWAPPINESS - INPUT_SWAPPINESS=${INPUT_SWAPPINESS:-$SWAPPINESS} - if [[ "$INPUT_SWAPPINESS" =~ ^[0-9]+$ && "$INPUT_SWAPPINESS" -ge 0 && "$INPUT_SWAPPINESS" -le 100 ]]; then - SWAPPINESS=$INPUT_SWAPPINESS - break - else - print_error "Invalid value for vm.swappiness. Must be between 0 and 100." - fi + read -rp "$(printf '%s' "${CYAN}Enter vm.swappiness (0-100) [default: $SWAPPINESS]: ${NC}")" INPUT + INPUT=${INPUT:-$SWAPPINESS} + if [[ "$INPUT" =~ ^[0-9]+$ && "$INPUT" -ge 0 && "$INPUT" -le 100 ]]; then SWAPPINESS=$INPUT; break; fi + print_error "Invalid value (0-100)." done while true; do - read -rp "$(printf '%s' "${CYAN}Enter vm.vfs_cache_pressure (1-1000) [default: $CACHE_PRESSURE]: ${NC}")" INPUT_CACHE_PRESSURE - INPUT_CACHE_PRESSURE=${INPUT_CACHE_PRESSURE:-$CACHE_PRESSURE} - if [[ "$INPUT_CACHE_PRESSURE" =~ ^[0-9]+$ && "$INPUT_CACHE_PRESSURE" -ge 1 && "$INPUT_CACHE_PRESSURE" -le 1000 ]]; then - CACHE_PRESSURE=$INPUT_CACHE_PRESSURE - break - else - print_error "Invalid value for vm.vfs_cache_pressure. Must be between 1 and 1000." - fi + read -rp "$(printf '%s' "${CYAN}Enter vm.vfs_cache_pressure (1-1000) [default: $CACHE_PRESSURE]: ${NC}")" INPUT + INPUT=${INPUT:-$CACHE_PRESSURE} + if [[ "$INPUT" =~ ^[0-9]+$ && "$INPUT" -ge 1 && "$INPUT" -le 1000 ]]; then CACHE_PRESSURE=$INPUT; break; fi + print_error "Invalid value (1-1000)." done else print_info "Using default swap settings (vm.swappiness=$SWAPPINESS, vm.vfs_cache_pressure=$CACHE_PRESSURE)." fi + local NEW_SWAP_CONFIG NEW_SWAP_CONFIG=$(mktemp) tee "$NEW_SWAP_CONFIG" > /dev/null < Date: Thu, 27 Nov 2025 14:26:57 +0000 Subject: [PATCH 02/10] improve configure_swap --- du_setup.sh | 84 ++++++++++++++++++++++++++++++++--------------------- 1 file changed, 51 insertions(+), 33 deletions(-) diff --git a/du_setup.sh b/du_setup.sh index 76bbfbb..91c039c 100644 --- a/du_setup.sh +++ b/du_setup.sh @@ -4885,21 +4885,16 @@ configure_swap() { fi print_section "Swap Configuration" - # Check for existing swap partition entries in fstab for awareness if lsblk -r | grep -q '\[SWAP\]'; then print_warning "Existing swap partition found on disk." fi # Detect active swap local existing_swap swap_type - - # --show=NAME,TYPE,SIZE ensures consistent column order existing_swap=$(swapon --show=NAME,TYPE,SIZE --noheadings --bytes 2>/dev/null | head -n 1 | awk '{print $1}' || true) if [[ -n "$existing_swap" ]]; then swap_type=$(swapon --show=NAME,TYPE,SIZE --noheadings | head -n 1 | awk '{print $2}') - - # Get human readable size for display using du (disk usage) local display_size display_size=$(du -h "$existing_swap" 2>/dev/null | awk '{print $1}' || echo "Unknown") @@ -4916,12 +4911,16 @@ configure_swap() { return 0 fi - # Comment out the partition in fstab to prevent it mounting on reboot - sed -i "s|^$existing_swap|#$existing_swap|" /etc/fstab - sed -i "s|^UUID=.*swap|#&|" /etc/fstab + sed -i "s|^${existing_swap}[[:space:]]|#&|" /etc/fstab + + local swap_uuid + swap_uuid=$(blkid -s UUID -o value "$existing_swap" 2>/dev/null || true) + if [[ -n "$swap_uuid" ]]; then + sed -i "s|^UUID=${swap_uuid}[[:space:]]|#&|" /etc/fstab + fi + print_success "Swap partition disabled and removed from fstab." - # Clear variable to trigger new file creation below existing_swap="" else print_info "Keeping existing swap partition." @@ -4935,16 +4934,19 @@ configure_swap() { while true; do read -rp "$(printf '%s' "${CYAN}Enter new swap size (e.g., 2G, 512M) [current: $display_size]: ${NC}")" SWAP_SIZE SWAP_SIZE=${SWAP_SIZE:-$display_size} - if validate_swap_size "$SWAP_SIZE"; then break; else print_error "Invalid size. Use format like '2G' or '512M'."; fi + if convert_to_mb "$SWAP_SIZE" >/dev/null; then + break + fi done - # Disk space check - local REQUIRED_SPACE AVAILABLE_SPACE - REQUIRED_SPACE=$(convert_to_bytes "$SWAP_SIZE") - AVAILABLE_SPACE=$(df -k / | tail -n 1 | awk '{print $4}') - # Convert available to bytes for comparison (df output is 1K blocks) - if (( (AVAILABLE_SPACE * 1024) < REQUIRED_SPACE )); then - print_error "Insufficient disk space. Required: $SWAP_SIZE, Available: $(numfmt --to=iec $((AVAILABLE_SPACE * 1024)))" + local REQUIRED_MB AVAILABLE_KB + if ! REQUIRED_MB=$(convert_to_mb "$SWAP_SIZE"); then return 1; fi + + AVAILABLE_KB=$(df -k / | tail -n 1 | awk '{print $4}') + + # Compare (Convert MB to KB for comparison) + if (( (AVAILABLE_KB / 1024) < REQUIRED_MB )); then + print_error "Insufficient disk space. Required: ${REQUIRED_MB}MB, Available: $((AVAILABLE_KB / 1024))MB" exit 1 fi @@ -4952,12 +4954,17 @@ configure_swap() { swapoff "$existing_swap" || { print_error "Failed to disable swap file."; exit 1; } print_info "Resizing swap file to $SWAP_SIZE..." + # Try fallocate first (fast), fallback to dd (compatible) if ! fallocate -l "$SWAP_SIZE" "$existing_swap" 2>/dev/null; then - print_warning "fallocate failed (filesystem might not support it). Using dd (slower)..." + print_warning "fallocate failed. Using dd (slower)..." rm -f "$existing_swap" - # Quoted command substitution for ShellCheck compliance - if ! dd if=/dev/zero of="$existing_swap" bs=1M count="$(convert_to_mb "$SWAP_SIZE")" status=progress; then + + # Check if dd supports progress + local dd_status="" + if dd --version 2>&1 | grep -q "progress"; then dd_status="status=progress"; fi + + if ! dd if=/dev/zero of="$existing_swap" bs=1M count="$REQUIRED_MB" $dd_status; then print_error "Failed to create swap file with dd." exit 1 fi @@ -4976,7 +4983,7 @@ configure_swap() { fi fi - # --- Case 3: Create New Swap (No swap exists, or partition was disabled above) --- + # --- Case 3: Create New Swap --- if [[ -z "$existing_swap" ]]; then if ! confirm "Configure a swap file (recommended for < 4GB RAM)?"; then print_info "Skipping swap configuration." @@ -4987,23 +4994,27 @@ configure_swap() { while true; do read -rp "$(printf '%s' "${CYAN}Enter swap file size (e.g., 2G, 512M) [2G]: ${NC}")" SWAP_SIZE SWAP_SIZE=${SWAP_SIZE:-2G} - if validate_swap_size "$SWAP_SIZE"; then break; else print_error "Invalid size. Use format like '2G' or '512M'."; fi + if convert_to_mb "$SWAP_SIZE" >/dev/null; then break; fi done - local REQUIRED_SPACE AVAILABLE_SPACE - REQUIRED_SPACE=$(convert_to_bytes "$SWAP_SIZE") - AVAILABLE_SPACE=$(df -k / | tail -n 1 | awk '{print $4}') + local REQUIRED_MB AVAILABLE_KB + if ! REQUIRED_MB=$(convert_to_mb "$SWAP_SIZE"); then return 1; fi + AVAILABLE_KB=$(df -k / | tail -n 1 | awk '{print $4}') - if (( (AVAILABLE_SPACE * 1024) < REQUIRED_SPACE )); then - print_error "Insufficient disk space. Required: $SWAP_SIZE, Available: $(numfmt --to=iec $((AVAILABLE_SPACE * 1024)))" + if (( (AVAILABLE_KB / 1024) < REQUIRED_MB )); then + print_error "Insufficient disk space. Required: ${REQUIRED_MB}MB, Available: $((AVAILABLE_KB / 1024))MB" exit 1 fi print_info "Creating $SWAP_SIZE swap file at /swapfile..." if ! fallocate -l "$SWAP_SIZE" /swapfile 2>/dev/null; then print_warning "fallocate failed. Using dd (slower)..." - # Quoted command substitution for ShellCheck compliance - if ! dd if=/dev/zero of=/swapfile bs=1M count="$(convert_to_mb "$SWAP_SIZE")" status=progress; then + + # Check dd status support + local dd_status="" + if dd --version 2>&1 | grep -q "progress"; then dd_status="status=progress"; fi + + if ! dd if=/dev/zero of=/swapfile bs=1M count="$REQUIRED_MB" $dd_status; then print_error "Failed to create swap file." rm -f /swapfile || true exit 1 @@ -5083,13 +5094,20 @@ EOF # Helper: Convert size (e.g., 2G) to MB for dd count convert_to_mb() { - local size="$1" - local num="${size%[MGmg]}" + local input="${1:-}" + local size="${input^^}" + size="${size// /}" + local num="${size%[MG]}" local unit="${size: -1}" - case "${unit^^}" in + if ! [[ "$num" =~ ^[0-9]+$ ]]; then + print_error "Invalid swap size format: '$input'. Expected format: 2G, 512M." >&2 + return 1 + fi + case "$unit" in G) echo "$((num * 1024))" ;; M) echo "$num" ;; - *) echo "1024" ;; # Default to 1GB if parsing fails + *) print_error "Unknown or missing unit in swap size: '$input'. Use 'M' or 'G' (e.g., 2G)." >&2 + return 1 ;; esac } From 1f0a20d9988f9a6e52ca179235702dd3d7067118 Mon Sep 17 00:00:00 2001 From: buildplan Date: Thu, 27 Nov 2025 15:06:12 +0000 Subject: [PATCH 03/10] Improved swap configuration with retries --- du_setup.sh | 97 +++++++++++++++++++++++++++++++---------------------- 1 file changed, 57 insertions(+), 40 deletions(-) diff --git a/du_setup.sh b/du_setup.sh index 91c039c..544cabc 100644 --- a/du_setup.sh +++ b/du_setup.sh @@ -4885,6 +4885,7 @@ configure_swap() { fi print_section "Swap Configuration" + # Check for existing swap partition entries in fstab if lsblk -r | grep -q '\[SWAP\]'; then print_warning "Existing swap partition found on disk." fi @@ -4912,7 +4913,6 @@ configure_swap() { fi sed -i "s|^${existing_swap}[[:space:]]|#&|" /etc/fstab - local swap_uuid swap_uuid=$(blkid -s UUID -o value "$existing_swap" 2>/dev/null || true) if [[ -n "$swap_uuid" ]]; then @@ -4920,7 +4920,6 @@ configure_swap() { fi print_success "Swap partition disabled and removed from fstab." - existing_swap="" else print_info "Keeping existing swap partition." @@ -4928,39 +4927,47 @@ configure_swap() { return 0 fi else - # --- Case 2: Swap File detected --- + # --- Case 2: Resize Existing Swap File --- if confirm "Modify existing swap file size?"; then - local SWAP_SIZE + local SWAP_SIZE REQUIRED_MB + while true; do read -rp "$(printf '%s' "${CYAN}Enter new swap size (e.g., 2G, 512M) [current: $display_size]: ${NC}")" SWAP_SIZE SWAP_SIZE=${SWAP_SIZE:-$display_size} - if convert_to_mb "$SWAP_SIZE" >/dev/null; then - break + # 1. Validate Format + if ! REQUIRED_MB=$(convert_to_mb "$SWAP_SIZE"); then + continue fi + # 2. Min Size + if (( REQUIRED_MB < 128 )); then + print_error "Swap size too small (minimum: 128M)." + continue + fi + # 3. Disk Space Check + local AVAILABLE_KB AVAILABLE_MB + AVAILABLE_KB=$(df -k / | tail -n 1 | awk '{print $4}') + AVAILABLE_MB=$((AVAILABLE_KB / 1024)) + if (( AVAILABLE_MB < REQUIRED_MB )); then + print_error "Insufficient disk space. Required: ${REQUIRED_MB}MB, Available: ${AVAILABLE_MB}MB" + # Suggest Max Safe Size (80% of free space) + local MAX_SAFE_MB=$(( AVAILABLE_MB * 80 / 100 )) + if (( MAX_SAFE_MB >= 128 )); then + print_info "Suggested maximum: ${MAX_SAFE_MB}M (leaves 20% free space)" + fi + continue + fi + break done - local REQUIRED_MB AVAILABLE_KB - if ! REQUIRED_MB=$(convert_to_mb "$SWAP_SIZE"); then return 1; fi - - AVAILABLE_KB=$(df -k / | tail -n 1 | awk '{print $4}') - - # Compare (Convert MB to KB for comparison) - if (( (AVAILABLE_KB / 1024) < REQUIRED_MB )); then - print_error "Insufficient disk space. Required: ${REQUIRED_MB}MB, Available: $((AVAILABLE_KB / 1024))MB" - exit 1 - fi - print_info "Disabling existing swap file..." swapoff "$existing_swap" || { print_error "Failed to disable swap file."; exit 1; } print_info "Resizing swap file to $SWAP_SIZE..." - - # Try fallocate first (fast), fallback to dd (compatible) + # Try fallocate, fallback to dd if ! fallocate -l "$SWAP_SIZE" "$existing_swap" 2>/dev/null; then print_warning "fallocate failed. Using dd (slower)..." rm -f "$existing_swap" - # Check if dd supports progress local dd_status="" if dd --version 2>&1 | grep -q "progress"; then dd_status="status=progress"; fi @@ -4990,44 +4997,52 @@ configure_swap() { return 0 fi - local SWAP_SIZE + local SWAP_SIZE REQUIRED_MB + while true; do read -rp "$(printf '%s' "${CYAN}Enter swap file size (e.g., 2G, 512M) [2G]: ${NC}")" SWAP_SIZE SWAP_SIZE=${SWAP_SIZE:-2G} - if convert_to_mb "$SWAP_SIZE" >/dev/null; then break; fi + # 1. Validate Format + if ! REQUIRED_MB=$(convert_to_mb "$SWAP_SIZE"); then + continue + fi + # 2. Min Size + if (( REQUIRED_MB < 128 )); then + print_error "Swap size too small (minimum: 128M)." + continue + fi + # 3. Disk Space Check + local AVAILABLE_KB AVAILABLE_MB + AVAILABLE_KB=$(df -k / | tail -n 1 | awk '{print $4}') + AVAILABLE_MB=$((AVAILABLE_KB / 1024)) + if (( AVAILABLE_MB < REQUIRED_MB )); then + print_error "Insufficient disk space. Required: ${REQUIRED_MB}MB, Available: ${AVAILABLE_MB}MB" + # Suggest Max Safe Size + local MAX_SAFE_MB=$(( AVAILABLE_MB * 80 / 100 )) + if (( MAX_SAFE_MB >= 128 )); then + print_info "Suggested maximum: ${MAX_SAFE_MB}M (leaves 20% free space)" + fi + continue + fi + break done - local REQUIRED_MB AVAILABLE_KB - if ! REQUIRED_MB=$(convert_to_mb "$SWAP_SIZE"); then return 1; fi - AVAILABLE_KB=$(df -k / | tail -n 1 | awk '{print $4}') - - if (( (AVAILABLE_KB / 1024) < REQUIRED_MB )); then - print_error "Insufficient disk space. Required: ${REQUIRED_MB}MB, Available: $((AVAILABLE_KB / 1024))MB" - exit 1 - fi - print_info "Creating $SWAP_SIZE swap file at /swapfile..." if ! fallocate -l "$SWAP_SIZE" /swapfile 2>/dev/null; then print_warning "fallocate failed. Using dd (slower)..." - - # Check dd status support local dd_status="" if dd --version 2>&1 | grep -q "progress"; then dd_status="status=progress"; fi - if ! dd if=/dev/zero of=/swapfile bs=1M count="$REQUIRED_MB" $dd_status; then print_error "Failed to create swap file." rm -f /swapfile || true exit 1 fi fi - if ! chmod 600 /swapfile || ! mkswap /swapfile >/dev/null || ! swapon /swapfile; then print_error "Failed to enable swap file." rm -f /swapfile || true exit 1 fi - - # Add to fstab if missing if ! grep -q '^/swapfile ' /etc/fstab; then echo '/swapfile none swap sw 0 0' >> /etc/fstab print_success "Swap entry added to /etc/fstab." @@ -5092,7 +5107,7 @@ EOF log "Swap configuration completed." } -# Helper: Convert size (e.g., 2G) to MB for dd count +# Helper: Convert size (e.g., 2G) to MB for validation/dd convert_to_mb() { local input="${1:-}" local size="${input^^}" @@ -5106,8 +5121,10 @@ convert_to_mb() { case "$unit" in G) echo "$((num * 1024))" ;; M) echo "$num" ;; - *) print_error "Unknown or missing unit in swap size: '$input'. Use 'M' or 'G' (e.g., 2G)." >&2 - return 1 ;; + *) + print_error "Unknown or missing unit in swap size: '$input'. Use 'M' or 'G'." >&2 + return 1 + ;; esac } From d3bb2dca3874971689c95878b4c0cad14bcdb1c2 Mon Sep 17 00:00:00 2001 From: buildplan Date: Thu, 27 Nov 2025 15:14:06 +0000 Subject: [PATCH 04/10] version and changelog --- du_setup.sh | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/du_setup.sh b/du_setup.sh index 544cabc..4edf8a6 100644 --- a/du_setup.sh +++ b/du_setup.sh @@ -1,8 +1,10 @@ #!/bin/bash # Debian and Ubuntu Server Hardening Interactive Script -# Version: 0.78.3 | 2025-11-26 +# Version: 0.78.4 | 2025-11-27 # Changelog: +# - v0.78.4: Improved configure_swap to detect swap partitions vs files. +# Prevents 'fallocate' crashes on physical partitions by offering to disable them or skip. # - v0.78.3: Update the summary to try to show the right environment detection based on finding personal VMs and cloud VPS. # Run update & upgrade in the final step to ensure system is fully updated after restart. # - v0.78.2: In configure_system set choosen hostname from collect_config in the /etc/hosts @@ -93,7 +95,7 @@ set -euo pipefail # --- Update Configuration --- -CURRENT_VERSION="0.78.3" +CURRENT_VERSION="0.78.4" SCRIPT_URL="https://raw.githubusercontent.com/buildplan/du_setup/refs/heads/main/du_setup.sh" CHECKSUM_URL="${SCRIPT_URL}.sha256" @@ -249,7 +251,7 @@ print_header() { printf '%s\n' "${CYAN}╔═════════════════════════════════════════════════════════════════╗${NC}" printf '%s\n' "${CYAN}║ ║${NC}" printf '%s\n' "${CYAN}║ DEBIAN/UBUNTU SERVER SETUP AND HARDENING SCRIPT ║${NC}" - printf '%s\n' "${CYAN}║ v0.78.3 | 2025-11-25 ║${NC}" + printf '%s\n' "${CYAN}║ v0.78.4 | 2025-11-27 ║${NC}" printf '%s\n' "${CYAN}║ ║${NC}" printf '%s\n' "${CYAN}╚═════════════════════════════════════════════════════════════════╝${NC}" printf '\n' From ff72d42b14701f4ad97a9a38529439061409835c Mon Sep 17 00:00:00 2001 From: buildplan Date: Thu, 27 Nov 2025 16:25:48 +0000 Subject: [PATCH 05/10] remove any unnecessary code --- du_setup.sh | 54 ++++++++++++++++++----------------------------------- 1 file changed, 18 insertions(+), 36 deletions(-) diff --git a/du_setup.sh b/du_setup.sh index 4edf8a6..17f8a38 100644 --- a/du_setup.sh +++ b/du_setup.sh @@ -2560,11 +2560,6 @@ validate_timezone() { [[ -e "/usr/share/zoneinfo/$tz" ]] } -validate_swap_size() { - local size_upper="${1^^}" # Convert to uppercase for case-insensitivity - [[ "$size_upper" =~ ^[0-9]+[MG]$ && "${size_upper%[MG]}" -ge 1 ]] -} - validate_ufw_port() { local port="$1" # Matches port (e.g., 8080) or port/protocol (e.g., 8080/tcp, 123/udp) @@ -2615,17 +2610,25 @@ validate_ip_or_cidr() { return 1 } -convert_to_bytes() { - local size_upper="${1^^}" # Convert to uppercase for case-insensitivity - local unit="${size_upper: -1}" - local value="${size_upper%[MG]}" - if [[ "$unit" == "G" ]]; then - echo $((value * 1024 * 1024 * 1024)) - elif [[ "$unit" == "M" ]]; then - echo $((value * 1024 * 1024)) - else - echo 0 +# Convert size (e.g., 2G) to MB for validation/dd +convert_to_mb() { + local input="${1:-}" + local size="${input^^}" + size="${size// /}" + local num="${size%[MG]}" + local unit="${size: -1}" + if ! [[ "$num" =~ ^[0-9]+$ ]]; then + print_error "Invalid swap size format: '$input'. Expected format: 2G, 512M." >&2 + return 1 fi + case "$unit" in + G) echo "$((num * 1024))" ;; + M) echo "$num" ;; + *) + print_error "Unknown or missing unit in swap size: '$input'. Use 'M' or 'G'." >&2 + return 1 + ;; + esac } # --- script update check --- @@ -5109,27 +5112,6 @@ EOF log "Swap configuration completed." } -# Helper: Convert size (e.g., 2G) to MB for validation/dd -convert_to_mb() { - local input="${1:-}" - local size="${input^^}" - size="${size// /}" - local num="${size%[MG]}" - local unit="${size: -1}" - if ! [[ "$num" =~ ^[0-9]+$ ]]; then - print_error "Invalid swap size format: '$input'. Expected format: 2G, 512M." >&2 - return 1 - fi - case "$unit" in - G) echo "$((num * 1024))" ;; - M) echo "$num" ;; - *) - print_error "Unknown or missing unit in swap size: '$input'. Use 'M' or 'G'." >&2 - return 1 - ;; - esac -} - configure_time_sync() { print_section "Time Synchronization" print_info "Ensuring chrony is active..." From e9161387c78831af4c2ffd15d145c8aca3c63bc7 Mon Sep 17 00:00:00 2001 From: buildplan Date: Thu, 27 Nov 2025 17:05:32 +0000 Subject: [PATCH 06/10] checksum v0.78.4 --- du_setup.sh.sha256 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/du_setup.sh.sha256 b/du_setup.sh.sha256 index c31dc46..0c9ee88 100644 --- a/du_setup.sh.sha256 +++ b/du_setup.sh.sha256 @@ -1 +1 @@ -fce60e9f65ec68b353215edf7a7da31caae62edc48944fd8fe6ea9883e95078d du_setup.sh +0c4b5dbda2844ba1220e996cb49ada3edfe1f6a9205c2f1bbaaec9cf9fbf9cc0 du_setup.sh From 428f6fa9d52e35918cf5c67d8595e17244dcb4dc Mon Sep 17 00:00:00 2001 From: buildplan Date: Thu, 27 Nov 2025 17:06:20 +0000 Subject: [PATCH 07/10] version and checksum --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ab8a214..bc5326d 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,9 @@ ----- -**Version:** v0.78.3 +**Version:** v0.78.4 -**Last Updated:** 2025-11-26 +**Last Updated:** 2025-11-27 **Compatible With:** @@ -87,12 +87,12 @@ sha256sum du_setup.sh Compare the output hash to the one below. They must match exactly. -`fce60e9f65ec68b353215edf7a7da31caae62edc48944fd8fe6ea9883e95078d` +`0c4b5dbda2844ba1220e996cb49ada3edfe1f6a9205c2f1bbaaec9cf9fbf9cc0` Or echo the hash to check, it should output: `du_setup.sh: OK` ```bash -echo fce60e9f65ec68b353215edf7a7da31caae62edc48944fd8fe6ea9883e95078d du_setup.sh | sha256sum --check +echo 0c4b5dbda2844ba1220e996cb49ada3edfe1f6a9205c2f1bbaaec9cf9fbf9cc0 du_setup.sh | sha256sum --check ``` ### 3. Run the Script From df67befa0c2b6ea71d5ccecc872339af12676285 Mon Sep 17 00:00:00 2001 From: buildplan Date: Thu, 27 Nov 2025 22:18:17 +0000 Subject: [PATCH 08/10] update message --- du_setup.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/du_setup.sh b/du_setup.sh index 17f8a38..c047b09 100644 --- a/du_setup.sh +++ b/du_setup.sh @@ -3,7 +3,7 @@ # Debian and Ubuntu Server Hardening Interactive Script # Version: 0.78.4 | 2025-11-27 # Changelog: -# - v0.78.4: Improved configure_swap to detect swap partitions vs files. +# - v0.78.4: Improved configure_swap to detect swap partitions vs files. # Prevents 'fallocate' crashes on physical partitions by offering to disable them or skip. # - v0.78.3: Update the summary to try to show the right environment detection based on finding personal VMs and cloud VPS. # Run update & upgrade in the final step to ensure system is fully updated after restart. @@ -2899,6 +2899,7 @@ collect_config() { install_packages() { print_section "Package Installation" print_info "Updating package lists and upgrading system..." + print_info "This may take a moment. Please wait..." if ! apt-get update -qq || ! DEBIAN_FRONTEND=noninteractive apt-get upgrade -y -qq; then print_error "Failed to update or upgrade system packages." exit 1 From c7e66378eea04d26d18a435f649d978fedb967a9 Mon Sep 17 00:00:00 2001 From: buildplan Date: Thu, 27 Nov 2025 22:18:44 +0000 Subject: [PATCH 09/10] checksum v0.78.4 --- du_setup.sh.sha256 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/du_setup.sh.sha256 b/du_setup.sh.sha256 index 0c9ee88..690446d 100644 --- a/du_setup.sh.sha256 +++ b/du_setup.sh.sha256 @@ -1 +1 @@ -0c4b5dbda2844ba1220e996cb49ada3edfe1f6a9205c2f1bbaaec9cf9fbf9cc0 du_setup.sh +d7378f43082166cad26c7b232f3cd01e778a3377dea996c3f434e0f483317659 du_setup.sh From be54f03de3f3a39e514b7ad86d8771a7f1d683f7 Mon Sep 17 00:00:00 2001 From: buildplan Date: Thu, 27 Nov 2025 22:19:53 +0000 Subject: [PATCH 10/10] version and checksum --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bc5326d..5bd3ae2 100644 --- a/README.md +++ b/README.md @@ -87,12 +87,12 @@ sha256sum du_setup.sh Compare the output hash to the one below. They must match exactly. -`0c4b5dbda2844ba1220e996cb49ada3edfe1f6a9205c2f1bbaaec9cf9fbf9cc0` +`d7378f43082166cad26c7b232f3cd01e778a3377dea996c3f434e0f483317659` Or echo the hash to check, it should output: `du_setup.sh: OK` ```bash -echo 0c4b5dbda2844ba1220e996cb49ada3edfe1f6a9205c2f1bbaaec9cf9fbf9cc0 du_setup.sh | sha256sum --check +echo d7378f43082166cad26c7b232f3cd01e778a3377dea996c3f434e0f483317659 du_setup.sh | sha256sum --check ``` ### 3. Run the Script