Skip to content

Commit fa6c4cc

Browse files
committed
refact: swap handling
1 parent d94cf73 commit fa6c4cc

1 file changed

Lines changed: 20 additions & 17 deletions

File tree

‎system/cuos/functions.sh‎

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ create_swap_and_resize_fs() {
244244
SWAP_SUBVOL="@swap"
245245
SWAP_MOUNTPOINT="/swap"
246246
SWAPFILE="$SWAP_MOUNTPOINT/swapfile"
247-
SWAP_SIZE_GB="$(jq_config ".swap_size // 8")"
247+
SWAP_SIZE_GB="$(jq_config ".swap_size // empty")"
248248
ROOT_MOUNT="/"
249249
ROOT_DEV=$(findmnt -n -o SOURCE --target "$ROOT_MOUNT")
250250

@@ -278,23 +278,35 @@ create_swap_and_resize_fs() {
278278

279279
if ! mountpoint -q "$SWAP_MOUNTPOINT"; then
280280
mkdir -p "$SWAP_MOUNTPOINT"
281-
mount -o subvol=$SWAP_SUBVOL "$ROOT_DEV" "$SWAP_MOUNTPOINT"
281+
mount -o "compress=no,noatime,subvol=$SWAP_SUBVOL" "$ROOT_DEV" "$SWAP_MOUNTPOINT"
282+
fi
283+
284+
if [[ -z "${SWAP_SIZE_GB}" ]]; then
285+
SWAP_SIZE_GB=8
286+
TARGET_SIZE="$((SWAP_SIZE_GB*1024*1024*1024))"
287+
FS_SIZE="$(df --output=size -B1 "$(dirname "$SWAPFILE")" | tail -n1)"
288+
MAX_SIZE="$((FS_SIZE / 4))"
289+
if [ "${TARGET_SIZE}" -gt "${MAX_SIZE}" ]; then
290+
TARGET_SIZE="${MAX_SIZE}"
291+
fi
292+
else
293+
TARGET_SIZE="$((SWAP_SIZE_GB*1024*1024*1024))"
282294
fi
283295

284296
RECREATE_SWAPFILE=false
285297
if [ ! -f "$SWAPFILE" ]; then
286298
RECREATE_SWAPFILE=true
287-
elif [ "$(stat -c%s "$SWAPFILE")" -lt $((SWAP_SIZE_GB*1024*1024*1024)) ]; then
299+
elif [ "$(stat -c%s "$SWAPFILE")" -lt "${TARGET_SIZE}" ]; then
288300
RECREATE_SWAPFILE=true
289301
fi
290302

291303
if $RECREATE_SWAPFILE; then
292304

293305
# Get available space in bytes on the filesystem containing the swap file
294-
AVAIL_BYTES=$(df --output=avail -B1 "$(dirname "$SWAPFILE")" | tail -n1)
306+
AVAIL_BYTES="$(df --output=avail -B1 "$(dirname "$SWAPFILE")" | tail -n1)"
295307

296308
# Check if available space is at least 1.5x the desired swap size (for safety)
297-
REQUIRED_BYTES=$((SWAP_SIZE_GB * 1024 * 1024 * 1024 * 3 / 2))
309+
REQUIRED_BYTES=$((TARGET_SIZE * 3 / 2))
298310

299311
if [ "$AVAIL_BYTES" -ge "$REQUIRED_BYTES" ]; then
300312
swapoff "$SWAPFILE" 2>/dev/null || true
@@ -304,18 +316,9 @@ create_swap_and_resize_fs() {
304316
chmod 600 "$SWAPFILE"
305317
mkswap "$SWAPFILE"
306318

307-
FSTAB_SWAP_MOUNT="LABEL=system $SWAP_MOUNTPOINT btrfs subvol=$SWAP_SUBVOL 0 0"
308-
FSTAB_SWAPFILE="$SWAPFILE none swap sw 0 0"
309-
310-
if ! grep -q "$FSTAB_SWAP_MOUNT" /etc/fstab; then
311-
echo "$FSTAB_SWAP_MOUNT" >> /etc/fstab
312-
fi
313-
if ! grep -q "$FSTAB_SWAPFILE" /etc/fstab; then
314-
echo "$FSTAB_SWAPFILE" >> /etc/fstab
315-
fi
316-
echo "Swap file created at $SWAPFILE with size ${SWAP_SIZE_GB}GB"
317-
318-
swapon "$SWAPFILE"
319319
fi
320320
fi
321+
if [[ -f "${SWAPFILE}" ]]; then
322+
swapon "$SWAPFILE"
323+
fi
321324
}

0 commit comments

Comments
 (0)