Created
February 2, 2025 05:10
-
-
Save MrDwarf7/a7d111b62f496d6fc6c80624f22c0f66 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import subprocess | |
import sys | |
import os | |
def run_cmd(cmd, check=True): | |
""" | |
Helper to run a command using subprocess. | |
If check=True, raises an exception on nonzero return. | |
""" | |
print(f"[CMD] {' '.join(cmd)}") | |
subprocess.run(cmd, check=check) | |
def get_uuid(device): | |
""" | |
Retrieve the UUID of a device using blkid. | |
""" | |
result = subprocess.run( | |
["blkid", "-s", "UUID", "-o", "value", device], | |
capture_output=True, | |
text=True, | |
check=True, | |
) | |
return result.stdout.strip() | |
def append_fstab_entries(mount_path, device_uuid): | |
""" | |
Append btrfs subvolume entries and swapfile entry to /mnt/etc/fstab | |
""" | |
etc_dir = os.path.join(mount_path, "etc") | |
os.makedirs(etc_dir, exist_ok=True) | |
fstab_path = os.path.join(etc_dir, "fstab") | |
# We assume user wants stadnard default mounts | |
# We may want to add other options like | |
fstab_entries = f""" | |
# BTRFS subvolume mounts | |
UUID={device_uuid} / btrfs defaults,subvol=@ 0 0 | |
UUID={device_uuid} /boot btrfs defaults,subvol=@boot 0 0 | |
UUID={device_uuid} /swap btrfs defaults,subvol=@swap 0 0 | |
UUID={device_uuid} /snapshots btrfs defaults,subvol=@snapshots 0 0 | |
UUID={device_uuid} /var btrfs defaults,subvol=@var 0 0 | |
UUID={device_uuid} /home btrfs defaults,subvol=@home 0 0 | |
UUID={device_uuid} /tmp btrfs defaults,subvol=@tmp 0 0 | |
# Swap file | |
/swap/swapfile none swap sw 0 0 | |
""" | |
print("Appending the following to /mnt/etc/fstab:\n") | |
print(fstab_entries) | |
with open(fstab_path, "a") as f: | |
f.write(fstab_entries) | |
def main(): | |
parser = argparse.ArgumentParser( | |
description="Get the UUID of the device and append to /etc/fstab." | |
) | |
parser.add_argument( | |
"--device", required=True, help="Path to the partition (e.g. /dev/nvme0n1p1)." | |
) | |
args = parser.parse_args() | |
device = args.device | |
print("Retrieving UUID of the device & Updating fstab entries...") | |
device_uuid = get_uuid(device) | |
append_fstab_entries("/mnt", device_uuid) | |
if __name__ == "__main__": | |
if os.geteuid() != 0: | |
print("This script must be run as root (sudo). Exiting.") | |
sys.exit(1) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment