1
0
Fork 0

transition to flakes (squashed commit)

This commit is contained in:
Pratham Patel 2024-04-07 16:38:52 +05:30
parent c1264b2d2d
commit c3a167f515
Signed by: thefossguy
SSH Key Fingerprint: SHA256:HwRBy9H1FYXWcv/Qi1WY3kmcVtGz2ydZuPJgD4pkusY
68 changed files with 2468 additions and 2076 deletions

1
.envrc Normal file
View File

@ -0,0 +1 @@
use flake

5
.gitignore vendored
View File

@ -1,2 +1,3 @@
out/
rpi-firmware/
*.iso
*.iso.sha*
result

49
flake.lock Normal file
View File

@ -0,0 +1,49 @@
{
"nodes": {
"home-manager": {
"inputs": {
"nixpkgs": [
"nixpkgs"
]
},
"locked": {
"lastModified": 1712386041,
"narHash": "sha256-dA82pOMQNnCJMAsPG7AXG35VmCSMZsJHTFlTHizpKWQ=",
"owner": "nix-community",
"repo": "home-manager",
"rev": "d6bb9f934f2870e5cbc5b94c79e9db22246141ff",
"type": "github"
},
"original": {
"owner": "nix-community",
"ref": "release-23.11",
"repo": "home-manager",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1712310679,
"narHash": "sha256-XgC/a/giEeNkhme/AV1ToipoZ/IVm1MV2ntiK4Tm+pw=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "72da83d9515b43550436891f538ff41d68eecc7f",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-23.11",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"home-manager": "home-manager",
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}

258
flake.nix Normal file
View File

@ -0,0 +1,258 @@
{
description = "Machines with Nix/NixOS";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-23.11";
home-manager = {
url = "github:nix-community/home-manager/release-23.11";
inputs.nixpkgs.follows = "nixpkgs";
};
};
outputs = { self, nixpkgs, home-manager, ... }:
let
nixpkgsRelease = "23.11";
mkForEachSupportedSystem = supportedSystems: f: nixpkgs.lib.genAttrs supportedSystems (system: f {
pkgs = import nixpkgs { inherit system; };
});
linuxSystems = {
aarch64 = "aarch64-linux";
x86_64 = "x86_64-linux";
riscv64 = "riscv64-linux";
};
darwinSystems = {
aarch64 = "aarch64-darwin";
x86_64 = "x86_64-darwin";
};
supportedLinuxSystems = nixpkgs.lib.attrValues linuxSystems;
supportedDarwinSystems = nixpkgs.lib.attrValues darwinSystems;
supportedSystems = supportedLinuxSystems ++ supportedDarwinSystems;
forEachSupportedLinuxSystem = mkForEachSupportedSystem supportedLinuxSystems;
forEachSupportedDarwinSystem = mkForEachSupportedSystem supportedDarwinSystems;
forEachSupportedSystem = mkForEachSupportedSystem supportedSystems;
systemUsers = {
# generate the `hashedPassword` using `mkpasswd`
root.hashedPassword = "$y$j9T$TBVrj7TnJZSu8RGTogysJ.$OJssY8qxjncolo/0i1bwWJ97QnsaVciGxFiSz46o9m5";
nixosIso = {
username = "nixos";
fullname = "nixos";
hashedPassword = "$y$j9T$VdsGhZ.x.ox6T3XVRNxAC.$1qrWehKr7kOW8VNQXXoLu8badBlDy05eKGwPawY/kM5";
enableLingering = true;
};
# actual, real system users
pratham = {
username = "pratham";
fullname = "Pratham Patel";
hashedPassword = "$y$j9T$nK7LF6Rdf9dHEZvp4GVJI/$JXKFIX3f.qdpih.1PBKZupzM5090jmaaS.1jxRMw9T0";
enableLingering = true;
};
};
gatewayAddr = "10.0.0.1";
ipv4PrefixLength = 24;
nixosHosts = {
# generate the `hostId` using `head -c4 /dev/urandom | od -A none -t x4 | xargs`
# "former" (now dead) "AI" "learning" PC (64GB; R9 3900XT; RTX 3070)
flameboi = {
hostname = "flameboi";
ipv4Address = "10.0.0.13";
networkingIface = "eth0";
hostId = "20c95fe3";
system = linuxSystems.x86_64;
};
# Raspberry Pi 4 Model B (4GB)
sentinel = {
hostname = "sentinel";
ipv4Address = "10.0.0.14";
networkingIface = "eth0";
hostId = "041d6ae7";
system = linuxSystems.aarch64;
};
# Raspberry Pi 4 Model B (8GB)
reddish = {
hostname = "reddish";
ipv4Address = "10.0.0.19";
networkingIface = "enabcm6e4ei0";
hostId = "996ccb68";
system = linuxSystems.aarch64;
};
# Radxa ROCK 5 Model B (16GB; RK3588)
mahadev = {
hostname = "mahadev";
ipv4Address = "10.0.0.21";
networkingIface = "enP4p65s0";
hostId = "c06c1a49";
system = linuxSystems.aarch64;
};
# Xunlong Orange Pi 5 (4GB; RK3588S)
pawandev = {
hostname = "pawandev";
ipv4Address = "10.0.0.22";
networkingIface = "eth0";
hostId = "2fefd3b2";
system = linuxSystems.aarch64;
};
# FriendlyElec NanoPC-T6 (16GB; RK3588)
stuti = {
hostname = "stuti";
ipv4Address = "10.0.0.23";
networkingIface = "enP4p65s0"; # second one from the right
hostId = "07ca9dd4";
system = linuxSystems.aarch64;
};
# StarFive VisionFive 2 (8GB; JH7110)
vaaman = {
hostname = "vaaman";
ipv4Address = "10.0.0.41";
networkingIface = "end0"; # first one from the right
hostId = "3c8077f9";
system = linuxSystems.riscv64;
};
# StarFive VisionFive 2 (4GB; JH7110)
vaayu = {
hostname = "vaayu";
ipv4Address = "10.0.0.42";
networkingIface = "end0"; # first one from the right
hostId = "d81cd923";
system = linuxSystems.riscv64;
};
};
# actual filesystems that I use
supportedFilesystemsSansZFS = [
"ext4"
"vfat"
"xfs"
];
mkNixosSystem = hostname: nixpkgs.lib.nixosSystem {
specialArgs = {
inherit (nixosHosts."${hostname}") hostname ipv4Address networkingIface hostId system;
inherit supportedFilesystemsSansZFS gatewayAddr ipv4PrefixLength;
forceLtsKernel = nixosHosts."${hostname}".forceLtsKernel or false;
systemUser = nixosHosts."${hostname}".systemUser or systemUsers.pratham;
};
modules = [
./nixos-configuration/hosts/${hostname}/default.nix
./nixos-configuration/hosts/hosts-common.nix
self.nixosModules.customNixosBaseModule
] ++ (nixosHosts."${hostname}".extraSystemModules or [ ]);
};
mkNonNixosHomeManager = pkgs: systemUser: home-manager.lib.homeManagerConfiguration {
inherit pkgs;
extraSpecialArgs = { inherit systemUser nixpkgsRelease; };
modules = [ ./nixos-configuration/home-manager/non-nixos-home.nix ];
};
buildNixosSystem = nixosConfigurationName: self.nixosConfigurations."${nixosConfigurationName}".config.system.build.toplevel;
buildNixosIso = systemArch: self.nixosConfigurations."iso-${systemArch}".config.system.build.isoImage;
buildHomeOf = system: username: self.homeConfigurations."${system}"."${username}".activationPackage;
in
{
nixosModules = {
customNixosBaseModule = {
_module.args = { inherit home-manager nixpkgsRelease; };
imports = [
{
system.stateVersion = "${nixpkgsRelease}";
hardware.enableRedistributableFirmware = true;
nixpkgs.config.allowUnfree = true; # allow non-FOSS pkgs
users.users.root.hashedPassword = "${systemUsers.root.hashedPassword}";
}
./nixos-configuration/configuration.nix
home-manager.nixosModules.home-manager
{
home-manager.useGlobalPkgs = true; # use the system's instance for pkgs
imports = [
./nixos-configuration/home-manager/nixos-home.nix
];
}
];
};
customNixosIsoModule = {
_module.args = {
inherit supportedFilesystemsSansZFS;
};
imports = [
./nixos-configuration/_iso/iso.nix
];
};
};
nixosConfigurations = {
flameboi = mkNixosSystem "flameboi";
sentinel = mkNixosSystem "sentinel";
reddish = mkNixosSystem "reddish";
mahadev = mkNixosSystem "mahadev";
pawandev = mkNixosSystem "pawandev";
stuti = mkNixosSystem "stuti";
vaaman = mkNixosSystem "vaaman";
vaayu = mkNixosSystem "vaayu";
iso-aarch64 = nixpkgs.lib.nixosSystem { system = linuxSystems.aarch64; modules = [ self.nixosModules.customNixosIsoModule ]; };
iso-riscv64 = nixpkgs.lib.nixosSystem { system = linuxSystems.riscv64; modules = [ self.nixosModules.customNixosIsoModule ]; };
iso-x86_64 = nixpkgs.lib.nixosSystem { system = linuxSystems.x86_64; modules = [ self.nixosModules.customNixosIsoModule ]; };
};
homeConfigurations = forEachSupportedSystem ({ pkgs, ... }: {
"${systemUsers.pratham.username}" = mkNonNixosHomeManager pkgs systemUsers.pratham;
});
machines = {
flameboi = buildNixosSystem "flameboi";
sentinel = buildNixosSystem "sentinel";
reddish = buildNixosSystem "reddish";
mahadev = buildNixosSystem "mahadev";
pawandev = buildNixosSystem "pawandev";
stuti = buildNixosSystem "stuti";
vaaman = buildNixosSystem "vaaman";
vaayu = buildNixosSystem "vaayu";
};
isos = {
aarch64 = buildNixosIso "aarch64";
riscv64 = buildNixosIso "riscv64";
x86_64 = buildNixosIso "x86_64";
};
# **THE SYSTEM NEEDS TO BE SPECIFIED!**
# so this would be '.#homeOf."$(uname -m)-$(uname -s | awk '{print tolower($0)}').$(whoami)"
homeOf = forEachSupportedSystem ({ pkgs, ... }: {
pratham = buildHomeOf pkgs.system "pratham";
});
devShells = forEachSupportedSystem ({ pkgs, ... }: {
default = pkgs.mkShell {
packages = with pkgs; [
git
nix-output-monitor
nixpkgs-fmt
parted
pciutils
tmux
vim
];
};
});
};
}

View File

@ -1,153 +1,100 @@
#!/usr/bin/env nix-shell
#!nix-shell -i bash --packages parted pciutils
# not using 'set -uf' because file globbing is necessary
# and we will be checking if vars are empty or not, manually
set -xe -o pipefail
#!/usr/bin/env bash
date +%Y/%m/%d\ %H:%M:%S
if [ "$(id -u)" -ne 0 ]; then
>&2 echo "$0: please run this script as root"
set -euf -o pipefail
if [[ "$(id -u)" != '0' ]]; then
echo 'ERROR: Please run this script as root'
exit 1
fi
if ! ping -c 1 google.com > /dev/null; then
>&2 echo "$0: not connected to the internet... exiting..."
echo 'ERROR: Not connected to the internet... exiting...'
exit 1
fi
if [ -z "${1}" ] || [ -z "${2}" ] || [ -z "${3}" ]; then
>&2 echo "$0: missing args for either 'OS drive', 'hostname' or 'disk partition layout'"
if [[ -z "${1:-}" || -z "${2:-}" ]]; then
# shellcheck disable=SC2016
echo 'ERROR: Insufficient arguments... $1:hostname, $2:target_disk'
exit 1
else
HOSTNAME="$1"
TARGET_DRIVE="$2"
fi
if [ -b "${TARGET_DRIVE}" ]; then
if echo "${TARGET_DRIVE}" | grep "sd\|vd" > /dev/null; then
INTERMEDIATE_PART="${TARGET_DRIVE}"
elif echo "${TARGET_DRIVE}" | grep "mmcblk\|nvme\|loop" > /dev/null; then
INTERMEDIATE_PART="${TARGET_DRIVE}p"
else
echo "ERROR: Unable to decide how to partition '${TARGET_DRIVE}'"
exit 1
fi
else
echo "ERROR: '${TARGET_DRIVE}' is not a block device"
exit 1
fi
if sudo dmesg | grep EFI | grep ' by Das U-Boot'; then
CAN_TOUCH_EFI_VARS='false'
TARGET_DRIVE_SIZE_IN_BYTES="$(blockdev --getsize64 "${TARGET_DRIVE}")"
TARGET_DRIVE_SIZE_IN_GIB="$(( TARGET_DRIVE_SIZE_IN_BYTES / 1024 / 1024 /1024 ))"
if [[ "${TARGET_DRIVE_SIZE_IN_GIB}" -lt 32 ]]; then
echo 'ERROR: Get a bigger disk'
exit 1
elif [[ "${TARGET_DRIVE_SIZE_IN_GIB}" -lt 64 ]]; then
ROOT_PART_SIZE=24
else
CAN_TOUCH_EFI_VARS='true'
BASE=1
while [[ "${TARGET_DRIVE_SIZE_IN_GIB}" -gt "${BASE}" ]]; do
BASE="$(( BASE * 2))"
done
ROOT_PART_SIZE=$(( BASE / 4 ))
fi
if [[ -d '/sys/class/power_supply/BAT0' ]]; then
BATTERY_POWERED_DEVICE='true'
else
BATTERY_POWERED_DEVICE='false'
fi
# '03' is the class number for Display controllers in PCI ID, so grep for it instead
if lspci -nn | grep '\[03' | grep -i 'AMD' > /dev/null; then
export GPU_AMD='true'
# we have this because 'grep -i ATI' also matches
# VGA comp**ati**ble controller [...] Red Hat, Inc. Virtio [...] GPU
elif lspci -nn | grep '\[03' | grep 'ATI' > /dev/null; then
export GPU_AMD='true'
fi
(lspci -nn | grep '\[03' | grep -i 'Intel' > /dev/null) && export GPU_INTEL='true'
(lspci -nn | grep '\[03' | grep -i 'Nvidia' > /dev/null) && export GPU_NVIDIA='true'
if [[ "${GPU_AMD}" == 'true' || "${GPU_INTEL}" == 'true' ]]; then
export OSS_GPU_DRIVERS='true'
elif [[ "${GPU_NVIDIA}" == 'true' ]]; then
export OSS_GPU_DRIVERS='false'
fi
grep 'AuthenticAMD' /proc/cmdline && export CPU_VENDOR='AMD'
grep 'GenuineIntel' /proc/cmdline && export CPU_VENDOR='Intel'
NETWORKING_HOSTID="$(head -c4 /dev/urandom | od -A none -t x4 | xargs)"
BOOT_UUID="$(head -c4 /dev/urandom | od -A none -t x4 | xargs)"
RPIF_UUID="$(head -c4 /dev/urandom | od -A none -t x4 | xargs)"
NETWORKING_INTERFACE="$(grep -i "eth\|enp\|enabcm\|wl" /proc/net/dev | sort | head -n 1 | awk -F : '{print $1}')"
TOTAL_MEM_KIB=$(grep 'MemTotal' /proc/meminfo | awk '{print $2}')
export OS_DRIVE="${1}"
export MACHINE_HOSTNAME="${2}"
export PARTITION_LAYOUT="${3}"
export HOSTNAME
export TARGET_DRIVE
export INTERMEDIATE_PART
export ROOT_PART_SIZE
export MOUNT_PATH='/mnt'
export CUSTOM_HOST_CONFIG="${MOUNT_PATH}/etc/nixos/host-specific-configuration.nix"
export TOTAL_MEM_GIB=$(( TOTAL_MEM_KIB / 1024 / 1024 ))
export RASP_PART_SIZE='64M'
export BOOT_PART_SIZE='1G'
export VARL_PART_SIZE='6G'
export BATTERY_POWERED_DEVICE
export NETWORKING_HOSTID
export BOOT_UUID
export RPIF_UUID
export NETWORKING_INTERFACE
export CAN_TOUCH_EFI_VARS
if [ "${TOTAL_MEM_GIB}" -lt 3 ]; then
>&2 echo "$0: You might get an OOM with less than 3GiB of RAM."
exit 1
fi
################################################################################
# installation actually starts here
################################################################################
set -x
# make sure that $MOUNT_PATH is empty
# otherwise, bad things happen
mount | grep " on ${MOUNT_PATH}" && umount --recursive --force "${MOUNT_PATH}"
if [ -b "${OS_DRIVE}" ]; then
if echo "${OS_DRIVE}" | grep "sd\|vd"; then
export INTERMEDIATE_PART="${OS_DRIVE}"
elif echo "${OS_DRIVE}" | grep "mmcblk\|nvme\|loop"; then
export INTERMEDIATE_PART="${OS_DRIVE}p"
else
>&2 echo "$0: unable to decide how to partition '${OS_DRIVE}'"
exit 1
fi
else
>&2 echo "$0: no such drive exists"
exit 1
# now we partition
./scripts/partition-disk.sh
# finally, we install NixOS
TOTAL_MEM_IN_KIB="$(grep 'MemTotal' /proc/meminfo | awk '{print $2}')"
TOTAL_MEM_IN_GIB="$(( TOTAL_MEM_IN_KIB / 1024 / 1024 ))"
MIN_MEMORY_IN_GIB='4'
if [[ "${TOTAL_MEM_IN_GIB}" -lt "${MIN_MEMORY_IN_GIB}" ]]; then
echo "WARNING: Total memory is less than ${MIN_MEMORY_IN_GIB} GB. You might get an OOM-kill ... "
fi
PARTITIONING_SCRIPT="$(pwd)/scripts/standard-partitions.sh"
if [[ "${PARTITION_LAYOUT}" == 'rpi' ]]; then
ROOT_PART_SIZE='80G'
PARTITIONING_SCRIPT="$(pwd)/scripts/raspberry-pi-partitions.sh"
elif [[ "${PARTITION_LAYOUT}" == 'desktop' ]]; then
ROOT_PART_SIZE='256G'
elif [[ "${PARTITION_LAYOUT}" == 'router' ]]; then
ROOT_PART_SIZE='32G'
elif [[ "${PARTITION_LAYOUT}" == 'virt' ]]; then
ROOT_PART_SIZE='48G'
else
>&2 echo "$0: invalid argument for 'disk partition layout'"
>&2 echo "$0: possible values are 'desktop', 'rpi', 'virt'"
exit 1
fi
export ROOT_PART_SIZE
# partition, format and mount
"${PARTITIONING_SCRIPT}"
# prepare installation
mkdir -p "${MOUNT_PATH}/etc/nixos"
nixos-generate-config --root "${MOUNT_PATH}"
if [[ "${PARTITION_LAYOUT}" == 'router' ]]; then
cp -v nixos-configuration/router.nix "${MOUNT_PATH}/etc/nixos/configuration.nix"
else
cp -vR nixos-configuration/* "${MOUNT_PATH}/etc/nixos"
fi
# all host-specific configuration
# - generate 'networking.hostId' for ZFS
# - enable Intel/AMD microcode loading if either CPU is detected
# - adding NVIDIA GPU support if it is detected
# - enabling KDE if the machine if $PARTITION_LAYOUT is either 'desktop'
# - enabling BSPWM if the machine if $PARTITION_LAYOUT is either 'virt'
# - enabling Podman containers if $MACHINE_HOSTNAME is 'reddish' (Raspberry Pi 4 Model B 8GB)
"$(pwd)/scripts/deviation.sh"
# wait for the user to verify the contents of '${MOUNT_PATH}/etc/nixos'
set +x
echo 'Every step except for installation has been performed.'
echo "Please review ${MOUNT_PATH}/etc/nixos/host-specific-configuration.nix"
set -x
read WAIT_UNCONDITIONALLY
# install NixOS
nixos-install --no-root-password --root "${MOUNT_PATH}" --show-trace
nix flake update
nixos-install \
--print-build-logs \
--show-trace \
--root ${MOUNT_PATH} \
--no-root-password \
--flake ".#${HOSTNAME}"
# very very initial setup for 'pratham'
cp "$(pwd)/scripts/chroot-as-pratham.sh" "${MOUNT_PATH}/home/pratham"
nixos-enter --root "${MOUNT_PATH}" -c 'sudo -i -u pratham bash /home/pratham/chroot-as-pratham.sh'
rm "${MOUNT_PATH}/home/pratham/chroot-as-pratham.sh"
# shellcheck disable=SC2207
REAL_USER_LIST=( $(awk -F ':' '{print $6}' "${MOUNT_PATH}/etc/passwd" | grep '/home/' | awk -F '/' '{print $NF}') )
CHROOT_USER_SCRIPT='chroot-user-setup.sh'
for NIXOS_USER in "${REAL_USER_LIST[@]}"; do
DESTINATION="/home/${NIXOS_USER}/${CHROOT_USER_SCRIPT}"
cp "scripts/${CHROOT_USER_SCRIPT}" "${MOUNT_PATH}${DESTINATION}"
nixos-enter --root "${MOUNT_PATH}" -c "sudo -i -u ${NIXOS_USER} bash ${DESTINATION}"
rm "${MOUNT_PATH}${DESTINATION}"
done
# done!
sync; sync; sync; sync;
sleep 10
sync; sync; sync; sync;
umount -R "${MOUNT_PATH}"

View File

@ -0,0 +1,64 @@
{ config
, lib
, pkgs
, modulesPath
, supportedFilesystemsSansZFS
, ...
}:
let
getGitRepos = pkgs.writeShellScriptBin "getGitRepos" ''
set -xeuf -o pipefail
while ! ping 1.1.1.1 -c 1 1>/dev/null || ! ping 8.8.8.8 -c 1 1>/dev/null; do
sleep 1
done
if [[ ! -d "$HOME/.dotfiles" ]]; then
git clone --bare https://gitlab.com/thefossguy/dotfiles.git "$HOME/.dotfiles"
git --git-dir="$HOME/.dotfiles" --work-tree="$HOME" checkout -f
rm -rf "$HOME/.config/nvim"
fi
if [[ ! -d "$HOME/my-git-repos/prathams-nixos" ]]; then
mkdir -vp "$HOME/my-git-repos"
git clone https://gitlab.com/thefossguy/prathams-nixos.git "$HOME/my-git-repos/prathams-nixos"
fi
'';
in
{
imports = [ (modulesPath + "/installer/cd-dvd/installation-cd-minimal.nix") ];
environment.systemPackages = with pkgs; [
# utilities necessary for installation
hdparm
parted
# getting, modifying and running the installer
git
neovim
rsync
tmux
vim
# monitoring
btop
htop
# ze script
getGitRepos
];
boot = {
kernelPackages = pkgs.linuxPackages_latest;
# since the latest kernel package is installed, there will be a ZFS conflict because
# 1. ZFS is developed out of tree and needs to catch up to the latest release
# 2. NixOS has ZFS enabled as a default
# so force a list of filesystems which I use; sans-ZFS
supportedFilesystems = lib.mkForce supportedFilesystemsSansZFS;
};
nix.settings.experimental-features = [ "nix-command" "flakes" ];
isoImage.squashfsCompression = "zstd -Xcompression-level 22";
}

View File

@ -1,11 +1,15 @@
{ pkgs, ... }:
{ config
, lib
, pkgs
, ...
}:
{
powerManagement.enable = true;
# Linux 6.4 and later is needed for AMD's 'amd-pstate' driver
# But the LTS kernel offered by NixOS 23.11 (1e2e384c5b7c) is 6.1.y
boot.kernelPackages = pkgs.linuxPackages_latest;
boot.kernelPackages = lib.mkForce pkgs.linuxPackages_latest;
services = {
thermald.enable = true;

View File

@ -0,0 +1,139 @@
{ config
, lib
, pkgs
, supportedFilesystemsSansZFS
, system
, ...
}:
{
boot = {
# `boot.loader.efi.canTouchEfiVariables` is set to false by default because
# `true` on a system with RO EFI vars fails, causing an error but
# `false` on a system with RW EFI vars does not fail
# this is a good default for x86 VMs too
# so it is always safe to assume that EFI vars cannot be modified
# but, we can always override it from the host-specific configuration file
blacklistedKernelModules = [ "nvidia" ];
loader.efi.canTouchEfiVariables = false;
plymouth.enable = lib.mkForce false;
supportedFilesystems = supportedFilesystemsSansZFS;
# present in the initrd but only loaded on-demand
# **ONLY INCLUDE MODULES NECESSARY TO MOUNT ROT ROOT DEVICE**
# please do not use this for including drivers for non-storage hardware
initrd.availableKernelModules = [
"nvme"
"usb_storage"
"usbhid"
];
kernelParams = [
"audit=0"
"ignore_loglevel"
"boot.shell_on_fail"
"fsck.mode=auto"
"fsck.repair=preen"
"plymouth.enable=0"
"rd.plymouth=0"
"no_console_suspend"
];
loader = {
timeout = lib.mkForce 10;
systemd-boot = {
enable = lib.mkForce true;
editor = lib.mkForce false;
};
};
kernel.sysctl = {
## Z-RAM-Swap
# Kernel docs: https://docs.kernel.org/admin-guide/sysctl/vm.html
# Pop!_OS "docs": https://github.com/pop-os/default-settings/pull/163/files
# Using zramswap, penalty shouldn't be that high, since if you are under
# high memory pressure, you likely are under high CPU load too
# at which point, you are performing computations and latency goes moot.
"vm.swappiness" = 180;
# Since zramSwap.algorithm is set to 'zstd', it is recommeded to set the
# 'vm.page-cluster' paramater to '0'.
"vm.page-cluster" = 0;
# Ensure that at-least 512MBytes of total memory is free to avoid system freeze.
# Not sure about the 512MBytes value since Pop!_OS sets it to 0.01% of total memory,
# which is roughly equal to 3.7MBytes on a 3700MBytes RPi4. The value of 512MBytes
# also does not leave lee-way for a 512M RPi Zero.
# A value too LOW will result in system freeze.
# A value too HIGH will result in OOM faster.
"vm.min_free_kbytes" = 512000;
# Disable 'vm.wwatermark_scale_factoratermark_boost_factor'.
# https://groups.google.com/g/linux.debian.user/c/YcDYu-jM-to
"vm.watermark_boost_factor" = 0;
# Start swapping when 70% of memory is full (30% of memory is left).
# 3000 is the MAX
"vm.watermark_scale_factor" = 3000;
# Increase the number of maximum mmaps a process may have (ZFS).
# 2147483642 = 1.99-ish GiB
"vm.max_map_count" = 2147483642;
# Same as `vm.dirty_ratio` but for background tasks
"vm.dirty_background_ratio" = 10;
# After how many centiseconds (1 second = 100 centiseconds) is dirty data
# committed to the disk
"vm.dirty_expire_centisecs" = 3000;
# Percentage of memory allowed to be filled with dirty data until it is
# committed to the disk
"vm.dirty_ratio" = 20;
# Interval between the kernel flusher threads that wake up to write old
# data to the disk. **Try keeping this less than half of whatever
# `vm.dirty_expire_centisecs`.**
# Check every N centisecs if data needs to be committed to the disk or not.
"vm.dirty_writeback_centisecs" = 1000;
# The Magic SysRq key is a key combo that allows users connected to the
# system console of a Linux kernel to perform some low-level commands.
# Disable it, since we don't need it, and is a potential security concern.
"kernel.sysrq" = 0;
## TCP hardening
# Prevent bogus ICMP errors from filling up logs.
"net.ipv4.icmp_ignore_bogus_error_responses" = 1;
# Reverse path filtering causes the kernel to do source validation of
# packets received from all interfaces. This can mitigate IP spoofing.
"net.ipv4.conf.default.rp_filter" = 1;
"net.ipv4.conf.all.rp_filter" = 1;
# Do not accept IP source route packets (we're not a router)
"net.ipv4.conf.all.accept_source_route" = 0;
"net.ipv6.conf.all.accept_source_route" = 0;
# Don't send ICMP redirects (again, we're on a router)
"net.ipv4.conf.all.send_redirects" = 0;
"net.ipv4.conf.default.send_redirects" = 0;
# Refuse ICMP redirects (MITM mitigations)
"net.ipv4.conf.all.accept_redirects" = 0;
"net.ipv4.conf.default.accept_redirects" = 0;
"net.ipv4.conf.all.secure_redirects" = 0;
"net.ipv4.conf.default.secure_redirects" = 0;
"net.ipv6.conf.all.accept_redirects" = 0;
"net.ipv6.conf.default.accept_redirects" = 0;
# Protects against SYN flood attacks
"net.ipv4.tcp_syncookies" = 1;
# Incomplete protection again TIME-WAIT assassination
"net.ipv4.tcp_rfc1337" = 1;
## TCP optimization
# TCP Fast Open is a TCP extension that reduces network latency by packing
# data in the senders initial TCP SYN. Setting 3 = enable TCP Fast Open for
# both incoming and outgoing connections:
"net.ipv4.tcp_fastopen" = 3;
# Bufferbloat mitigations + slight improvement in throughput & latency
"net.ipv4.tcp_congestion_control" = "bbr";
"net.core.default_qdisc" = "cake";
## Allow rootless containers to get pinged and/or ping each other
"net.ipv4.ping_group_range" = "0 165536";
};
};
}

View File

@ -1,568 +1,25 @@
{ lib, pkgs, ... }:
let
NixOSRelease = "23.11";
home-manager = builtins.fetchTarball "https://github.com/nix-community/home-manager/archive/release-${NixOSRelease}.tar.gz";
prathamsHome = "/home/pratham";
scriptsDir = "${prathamsHome}/.local/scripts";
sudoRules = with pkgs; [
{ package = coreutils; command = "sync"; }
{ package = hdparm; command = "hdparm"; }
{ package = nix; command = "nix-collect-garbage"; }
{ package = nixos-rebuild; command = "nixos-rebuild"; }
{ package = nvme-cli; command = "nvme"; }
{ package = systemd; command = "poweroff"; }
{ package = systemd; command = "reboot"; }
{ package = systemd; command = "shutdown"; }
{ package = systemd; command = "systemctl"; }
{ package = util-linux; command = "dmesg"; }
];
mkSudoRule = rule: {
command = "${rule.package}/bin/${rule.command}";
options = [ "NOPASSWD" ];
};
sudoCommands = map mkSudoRule sudoRules;
whatIGetForSupportingTheRaspberryPiFoundation = pkgs.writeShellScriptBin "populate-boot-for-raspberry-pi" ''
set -xe
if grep 'Raspberry Pi' /proc/device-tree/model > /dev/null; then
cp "${pkgs.ubootRaspberryPi4_64bit}/u-boot.bin" /boot
cp -r "${pkgs.raspberrypifw}/share/raspberrypi/boot/"* /boot
cat << EOF > /boot/config.txt
enable_uart=1
avoid_warnings=1
arm_64bit=1
kernel=u-boot.bin
[pi4]
#hdmi_enable_4kp60=1
arm_boost=1
fi
'';
OVMFBinName = if pkgs.stdenv.isAarch64 then "AAVMF"
else (
if pkgs.stdenv.isx86_64 then "OVMF"
else ""
);
in
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
imports = [
./host-specific-configuration.nix # specific to this host
(import "${home-manager}/nixos") # aye, home-manager
./hardware-configuration.nix # generated by 'nixos-generate-config'
./bootloader-configuration.nix
./misc-configuration.nix
./network-configuration.nix
./packages/system-packages.nix
./systemd-services/system-services.nix
./user-configuration.nix
./virtualisation-configuration.nix
];
# {{ packages section }}
nixpkgs.config.allowUnfree = true; # allow non-FOSS pkgs
environment.systemPackages = with pkgs; [
# base system packages + packages what I *need*
cloud-utils # provides growpart
dig # provides dig and nslookup
dmidecode
file
findutils
gawk
gettext # for translation (human lang; Eng <-> Hindi)
gnugrep
gnused
hdparm
inotify-tools
iproute2
iputils
linux-firmware
lsof
minisign
nvme-cli
parallel
pciutils # provides lspci and setpci
pinentry # pkg summary: GnuPGs interface to passphrase input
procps # provides pgrep, kill, watch, ps, pidof, uptime, sysctl, free, etc
psmisc # provides killall, fuser, pslog, pstree, etc
pv
python3Minimal
rsync
smartmontools
tree
usbutils
util-linux # provides blkid, losetup, lsblk, rfkill, fallocate, dmesg, etc
vim # it is a necessity
wol
# shells
dash
# download clients
curl
wget
# compression and decompression
bzip2
gnutar
gzip
unzip
xz
zip
zstd
# programming tools + compilers
#cargo-deb # generate .deb packages solely based on Cargo.toml
#cargo-ndk # extension for building Android NDK projects
#binutils # provides readelf, objdump, strip, as, objcopy (GNU; not LLVM)
#gdb
b4 # applying patches from mailing lists
cargo-audit # audit crates for security vulnerabilities
cargo-benchcmp # compare Rust micro-benchmarks
cargo-binstall # install Rust binaries instead of building them from src
cargo-bisect-rustc # find exactly which rustc commit/release-version which prevents your code from building now
cargo-bloat # find what takes the most space in the executable
cargo-cache # manage cargo cache (${CARGO_HOME}); print and remove dirs selectively
cargo-chef # for speeding up container builds using layer caching
cargo-deps # build dependency graph of Rust projects
cargo-dist # distribute on crates.io
cargo-flamegraph # flamegraphs without Perl or pipes
cargo-hack # build project with all the possible variations of options/flags and check which ones fail and/or succeed
cargo-outdated # show outdated deps
cargo-profiler # profile Rust binaries
cargo-public-api # detect breaking API changes and semver violations
cargo-show-asm # display ASM, LLVM-IR, MIR and WASM for the Rust src
cargo-sweep # cleanup unused build files
cargo-udeps # find unused dependencies
cargo-update # update installed binaries
cargo-valgrind
cargo-vet # ensure that the third-party dependencies are audited by a trusted source
cargo-watch # run cargo commands when the src changes
rustup # provides rustfmt, cargo-clippy, rustup, cargo, rust-lldb, rust-analyzer, rustc, rust-gdb, cargo-fmt
# e-mail
aerc
protonmail-bridge
thunderbird
# power management
acpi
lm_sensors
# dealing with other distro's packages
dpkg
rpm
# for media consumption, manipulation and metadata info
ffmpeg
imagemagick
mediainfo
# network monitoring
iperf # this is iperf3
iperf2 # this is what is usually 'iperf' on other distros
nload
# other utilities
asciinema
buildah
fzf
parted
picocom
ubootTools
ventoy
# utilities written in Rust
choose
du-dust
dua
fd
hyperfine
procs
sd
tre-command
# virtualisation
qemu_kvm
# tools specific to Nix
nix-output-monitor
nvd # diff between NixOS generations
nix-prefetch
nix-prefetch-git
nix-prefetch-github
];
programs = {
adb.enable = true;
bandwhich.enable = true;
ccache.enable = true;
command-not-found.enable = true;
dconf.enable = true;
git.enable = true;
gnupg.agent.enable = true;
htop.enable = true;
iotop.enable = true;
mtr.enable = true;
skim.fuzzyCompletion = true;
sniffnet.enable = true;
tmux.enable = true;
traceroute.enable = true;
trippy.enable = true;
usbtop.enable = true;
bash = {
enableCompletion = true;
# notifications when long-running terminal commands complete
undistractMe = {
enable = true;
playSound = true;
timeout = 300; # notify only if said command has been running for this many seconds
};
# aliases for the root user
# doesn't affect 'pratham' since there is an `unalias -a` in /home/pratham/.bashrc
shellAliases = {
"e" = "${pkgs.vim}/bin/vim";
};
};
nano = {
enable = true;
syntaxHighlight = true;
};
};
# {{ user configuration }}
users = {
allowNoPasswordLogin = false;
defaultUserShell = pkgs.bash;
enforceIdUniqueness = true;
mutableUsers = false; # setting this to `false` means users/groups cannot be added with `useradd`/`groupadd`
users.root.hashedPassword = "$6$cxSzljtGpFNLRhx1$0HvOs4faEzUw9FYUF8ifOwBPwHsGVL7HenQMCOBNwqknBFHSlA6NIDO7U36HeQ/C9FN/B.dP.WBg3MzqQcubr0";
users.pratham = {
createHome = true;
description = "Pratham Patel";
group = "pratham";
hashedPassword = "$6$QLxAJcAeYARWFnnh$MaicewslNWkf/D8o6lDAWA1ECLMZLL3KWgIqPKuu/Qgt3iDBCEbEFjt3CUI4ENifvXW/blpze8IYeWhDjaKgS1";
home = "${prathamsHome}";
isNormalUser = true; # normal vs system is really about a "real" vs "builder" user, respectively
isSystemUser = false;
linger = true;
subGidRanges = [ { startGid = 10000; count = 65536; } ];
subUidRanges = [ { startUid = 10000; count = 65536; } ];
uid = 1000;
extraGroups = [
"adbusers"
"adm"
"dialout"
"ftp"
"games"
"http"
"kvm"
"libvirt"
"libvirtd"
"log"
"mlocate"
"networkmanager"
"podman"
"qemu-libvirtd"
"rfkill"
"sshusers"
"sys"
"systemd-journal"
"uucp"
"video"
"wheel"
"zfs-read"
];
};
groups.pratham = {
name = "pratham";
gid = 1000;
};
};
# {{ sudo configuration }}
security.sudo = {
enable = true;
execWheelOnly = true;
keepTerminfo = true;
wheelNeedsPassword = true;
extraRules = [{
users = [ "pratham" ];
commands = sudoCommands;
}];
};
# {{ home-manager configuration }}
# call the home-manager configuration directly
# without having to depend on a $HOME/.config/home-manager/{home,flake}.nix
home-manager.users.pratham = { lib, pkgs, ... }: {
home.stateVersion = "${NixOSRelease}";
programs = {
aria2.enable = true;
bat.enable = true;
bottom.enable = true;
broot.enable = true;
btop.enable = true;
ripgrep.enable = true;
tealdeer.enable = true;
yt-dlp.enable = true;
zoxide.enable = true;
direnv = {
enable = true;
enableBashIntegration = true;
nix-direnv.enable = true;
};
neovim = {
enable = true;
extraPackages = with pkgs; [
clang-tools # provides clangd
gcc # for nvim-tree's parsers
lldb # provides lldb-vscode
lua-language-server
nil # language server for Nix
nixpkgs-fmt
nodePackages.bash-language-server
ruff
shellcheck
tree-sitter # otherwise nvim complains that the binary 'tree-sitter' is not found
];
};
};
# for raw QEMU VMs
home.activation = {
OVMFActivation = lib.hm.dag.entryAfter [ "installPackages" ] (if pkgs.stdenv.isx86_64 then ''
EDKII_CODE_NIX="${pkgs.OVMF}/FV/${OVMFBinName}_CODE.fd"
EDKII_VARS_NIX="${pkgs.OVMF}/FV/${OVMFBinName}_VARS.fd"
EDKII_DIR_HOME="$HOME/.local/share/edk2"
EDKII_CODE_HOME="$EDKII_DIR_HOME/EDKII_CODE"
EDKII_VARS_HOME="$EDKII_DIR_HOME/EDKII_VARS"
if [ -d "$EDKII_DIR_HOME" ]; then
rm -rf "$EDKII_DIR_HOME"
fi
mkdir -vp "$EDKII_DIR_HOME"
cp "$EDKII_CODE_NIX" "$EDKII_CODE_HOME"
cp "$EDKII_VARS_NIX" "$EDKII_VARS_HOME"
chown pratham:pratham "$EDKII_CODE_HOME" "$EDKII_VARS_HOME"
chmod 644 "$EDKII_CODE_HOME" "$EDKII_VARS_HOME"
'' else "");
};
# for libvirt, virt-manager, virsh
xdg.configFile = {
"libvirt/qemu.conf" = {
enable = true;
text = ''
nvram = [ "/run/libvirt/nix-ovmf/AAVMF_CODE.fd:/run/libvirt/nix-ovmf/AAVMF_VARS.fd", "/run/libvirt/nix-ovmf/OVMF_CODE.fd:/run/libvirt/nix-ovmf/OVMF_VARS.fd" ]
'';
};
};
dconf.settings = {
"org/virt-manager/virt-manager/connections" = {
autoconnect = ["qemu:///system"];
uris = ["qemu:///system"];
};
};
systemd.user.services = {
"dotfiles-pull" = {
Unit = {
Description = "Pull dotfiles";
};
Service = {
ExecStart = "${pkgs.dash}/bin/dash ${scriptsDir}/other-common-scripts/dotfiles-pull.sh";
Environment = [ "\"PATH=${pkgs.git}/bin:${pkgs.openssh}/bin\"" ];
Type = "oneshot";
};
Install = {
WantedBy = [ "default.target" ];
};
};
"flatpak-manage" = {
Unit = {
Description = "Manage flatpaks on system";
};
Service = {
ExecStart = "${pkgs.bash}/bin/bash ${scriptsDir}/other-common-scripts/flatpak-manage.sh";
Environment = [ "\"PATH=${pkgs.gnugrep}/bin\"" ];
Type = "oneshot";
};
Install = {
WantedBy = [ "default.target" ];
};
};
"nixos-config-pull" = {
Unit = {
Description = "Pull NixOS configuration";
};
Service = {
ExecStart = "${pkgs.dash}/bin/dash ${scriptsDir}/nixos/nixos-config-pull.sh";
Environment = [ "\"PATH=${pkgs.git}/bin:${pkgs.openssh}/bin\"" ];
Type = "oneshot";
};
Install = {
WantedBy = [ "default.target" ];
};
};
"update-rust" = {
Unit = {
Description = "Upgrade the Rust toolchain";
};
Service = {
ExecStart = "${pkgs.dash}/bin/dash ${scriptsDir}/other-common-scripts/rust-manage.sh";
Environment = [ "\"PATH=${pkgs.procps}/bin:${pkgs.rustup}/bin\"" ];
Type = "oneshot";
};
Install = {
WantedBy = [ "default.target" ];
};
};
};
systemd.user.timers = {
"dotfiles-pull" = {
Unit = {
};
Timer = {
OnCalendar = "*-*-* 23:00:00";
Unit = "dotfiles-pull.service";
};
Install = {
WantedBy = [ "timers.target" ];
};
};
"flatpak-manage" = {
Unit = {
};
Timer = {
OnBootSec = "now";
OnCalendar = "Mon *-*-* 04:00:00";
Unit = "flatpak-manage.service";
};
Install = {
WantedBy = [ "timers.target" ];
};
};
"nixos-config-pull" = {
Unit = {
};
Timer = {
OnCalendar = "*-*-* 23:00:00";
Unit = "nixos-config-pull.service";
};
Install = {
WantedBy = [ "timers.target" ];
};
};
"update-rust" = {
Unit = {
};
Timer = {
OnBootSec = "now";
OnCalendar = "Mon *-*-* 04:00:00";
Unit = "update-rust.service";
};
Install = {
WantedBy = [ "timers.target" ];
};
};
};
};
# {{ system services' "parameters" go here }}
environment.etc."resolv.conf".mode = "direct-symlink";
services.resolved = {
enable = true;
fallbackDns = [
"1.1.1.1"
"1.0.0.1"
"8.8.8.8"
"8.8.4.4"
];
};
services = {
fwupd.enable = true;
journald.storage = "persistent";
logrotate.enable = true;
timesyncd.enable = true; # NTP
udisks2.enable = true;
locate = {
enable = true;
interval = "hourly";
localuser = null;
package = pkgs.mlocate;
pruneBindMounts = true;
prunePaths = [
"${prathamsHome}/.cache"
"${prathamsHome}/.dotfiles"
"${prathamsHome}/.local/share"
"${prathamsHome}/.local/state"
"${prathamsHome}/.nix-defexpr"
"${prathamsHome}/.nix-profile"
"${prathamsHome}/.nvim/undodir"
"${prathamsHome}/.rustup"
"${prathamsHome}/.vms"
"${prathamsHome}/.zkbd"
"/nix"
];
};
# sshd_config
openssh = {
enable = true;
ports = [ 22 ];
openFirewall = true;
settings = {
Protocol = 2;
MaxAuthTries = 2;
PermitEmptyPasswords = lib.mkForce false;
PasswordAuthentication = lib.mkForce false;
PermitRootLogin = lib.mkForce "prohibit-password";
X11Forwarding = false;
};
};
};
systemd.timers = {
"update-nixos-config" = {
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = "*-*-* 23:30:00";
Unit = "update-nixos-config.service";
};
};
};
systemd.services = {
"update-nixos-config" = {
serviceConfig = {
Type = "oneshot";
User = "root";
ExecStart = "${pkgs.coreutils}/bin/cp -fR ${prathamsHome}/my-git-repos/pratham/prathams-nixos/nixos-configuration/. /etc/nixos";
};
};
};
# {{ configuration options related to Nix and NixOS }}
nix = {
checkAllErrors = true;
checkConfig = true;
gc = {
automatic = true;
dates = "*-*-* 23:00:00"; # everyday, at 23:00
@ -576,286 +33,7 @@ in
log-lines = 9999;
sandbox = true;
show-trace = true;
trusted-users = [ "root" "pratham" ];
trusted-users = [ "root" "${systemUser.username}" ];
};
};
system = {
stateVersion = "${NixOSRelease}"; # release version of NixOS
# TODO: after adding `ubootRaspberryPi_64bit` to nixpkgs
# also remove: `scripts/{get-raspi-4-firmware,raspberry-pi-partitions}.sh`
#build.separateActivationScript = "${whatIGetForSupportingTheRaspberryPiFoundation}/bin/populate-boot-for-raspberry-pi";
autoUpgrade = {
enable = true;
dates = "daily"; # *-*-* 00:00:00
allowReboot = false;
operation = "boot";
persistent = true;
};
};
# {{ networking section }}
systemd.network = {
enable = true;
wait-online = {
enable = true;
anyInterface = true;
};
};
networking = {
firewall.enable = false; # this uses iptables AFAIK, use nftables instead
networkmanager.enable = true;
nftables.enable = true;
wireless.enable = false; # this enabled 'wpa_supplicant', use networkmanager instead
nameservers = [
"1.1.1.1"
"1.0.0.1"
"8.8.8.8"
"8.8.4.4"
];
};
# {{ misc }}
time = {
timeZone = "Asia/Kolkata";
hardwareClockInLocalTime = true;
};
security = {
polkit.enable = true;
virtualisation.flushL1DataCache = "always";
};
console = {
enable = true;
earlySetup = true;
};
# {{ environment... stuff }}
i18n = {
defaultLocale = "en_IN";
extraLocaleSettings = {
LC_ADDRESS = "en_IN";
LC_IDENTIFICATION = "en_IN";
LC_MEASUREMENT = "en_IN";
LC_MONETARY = "en_IN";
LC_NAME = "en_IN";
LC_NUMERIC = "en_IN";
LC_PAPER = "en_IN";
LC_TELEPHONE = "en_IN";
LC_TIME = "en_IN";
};
};
environment = {
homeBinInPath = true;
localBinInPath = true;
variables = {
# for 'sudo -e'
EDITOR = "nvim";
VISUAL = "nvim";
# systemd
SYSTEMD_PAGER = "";
SYSTEMD_EDITOR = "nvim";
TERM = "xterm-256color";
# set locale manually because even though NixOS handles the 'en_IN' locale
# it doesn't append the string '.UTF-8' to LC_*
# but, UTF-8 **is supported**, so just go ahead and set it manually
LANG = lib.mkDefault "en_IN.UTF-8";
LC_ADDRESS = lib.mkDefault "en_IN.UTF-8";
LC_COLLATE = "en_IN.UTF-8";
LC_CTYPE = "en_IN.UTF-8";
LC_IDENTIFICATION = lib.mkDefault "en_IN.UTF-8";
LC_MEASUREMENT = lib.mkDefault "en_IN.UTF-8";
LC_MESSAGES = "en_IN.UTF-8";
LC_MONETARY = lib.mkDefault "en_IN.UTF-8";
LC_NAME = lib.mkDefault "en_IN.UTF-8";
LC_NUMERIC = lib.mkDefault "en_IN.UTF-8";
LC_PAPER = lib.mkDefault "en_IN.UTF-8";
LC_TELEPHONE = lib.mkDefault "en_IN.UTF-8";
LC_TIME = lib.mkDefault "en_IN.UTF-8";
LC_ALL = "";
# idk why, but some XDG vars aren't set, the missing ones are now set according to the
# spec: (https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html)
XDG_DATA_HOME = "$HOME/.local/share";
XDG_CONFIG_HOME = "$HOME/.config";
XDG_STATE_HOME = "$HOME/.local/state";
XDG_CACHE_HOME = "$HOME/.cache";
};
};
# yes, I want docs
documentation = {
enable = true;
dev.enable = true;
doc.enable = true;
info.enable = true;
man = {
enable = true;
generateCaches = true;
};
};
# {{ virtualisation and container settings }}
virtualisation = {
oci-containers.backend = "podman";
libvirtd = {
enable = true;
onShutdown = "shutdown";
allowedBridges = [ "virbr0" ];
qemu = {
package = pkgs.qemu_kvm;
runAsRoot = false; # not sure about this
swtpm.enable = true;
ovmf = {
enable = true;
packages = [ pkgs.OVMF ];
};
verbatimConfig = ''
user = "pratham"
group = "pratham"
'';
};
};
podman = {
enable = true;
dockerCompat = true;
dockerSocket.enable = true;
networkSocket.openFirewall = true;
extraPackages = [ pkgs.buildah ];
defaultNetwork.settings = {
dns_enabled = true;
};
autoPrune = {
enable = true;
dates = "weekly";
flags = [ "--all" ];
};
};
};
boot = {
kernelParams = [
"audit=0"
"ignore_loglevel"
"boot.shell_on_fail"
"fsck.mode=auto"
"fsck.repair=preen"
"plymouth.enable=0"
"rd.plymouth=0"
"no_console_suspend"
];
supportedFilesystems = [
"ext4"
"f2fs"
"vfat"
"xfs"
];
kernel.sysctl = {
## Z-RAM-Swap
# Kernel docs: https://docs.kernel.org/admin-guide/sysctl/vm.html
# Pop!_OS "docs": https://github.com/pop-os/default-settings/pull/163/files
# Using zramswap, penalty shouldn't be that high, since if you are under
# high memory pressure, you likely are under high CPU load too
# at which point, you are performing computations and latency goes moot.
"vm.swappiness" = 180;
# Since zramSwap.algorithm is set to 'zstd', it is recommeded to set the
# 'vm.page-cluster' paramater to '0'.
"vm.page-cluster" = 0;
# Ensure that at-least 512MBytes of total memory is free to avoid system freeze.
# Not sure about the 512MBytes value since Pop!_OS sets it to 0.01% of total memory,
# which is roughly equal to 3.7MBytes on a 3700MBytes RPi4. The value of 512MBytes
# also does not leave lee-way for a 512M RPi Zero.
# A value too LOW will result in system freeze.
# A value too HIGH will result in OOM faster.
"vm.min_free_kbytes"= 512000;
# Disable 'vm.wwatermark_scale_factoratermark_boost_factor'.
# https://groups.google.com/g/linux.debian.user/c/YcDYu-jM-to
"vm.watermark_boost_factor" = 0;
# Start swapping when 70% of memory is full (30% of memory is left).
# 3000 is the MAX
"vm.watermark_scale_factor" = 3000;
# Increase the number of maximum mmaps a process may have (ZFS).
# 2147483642 = 1.99-ish GiB
"vm.max_map_count" = 2147483642;
# Same as `vm.dirty_ratio` but for background tasks
"vm.dirty_background_ratio" = 10;
# After how many centiseconds (1 second = 100 centiseconds) is dirty data
# committed to the disk
"vm.dirty_expire_centisecs" = 3000;
# Percentage of memory allowed to be filled with dirty data until it is
# committed to the disk
"vm.dirty_ratio" = 20;
# Interval between the kernel flusher threads that wake up to write old
# data to the disk. **Try keeping this less than half of whatever
# `vm.dirty_expire_centisecs`.**
# Check every N centisecs if data needs to be committed to the disk or not.
"vm.dirty_writeback_centisecs" = 1000;
# The Magic SysRq key is a key combo that allows users connected to the
# system console of a Linux kernel to perform some low-level commands.
# Disable it, since we don't need it, and is a potential security concern.
"kernel.sysrq" = 0;
## TCP hardening
# Prevent bogus ICMP errors from filling up logs.
"net.ipv4.icmp_ignore_bogus_error_responses" = 1;
# Reverse path filtering causes the kernel to do source validation of
# packets received from all interfaces. This can mitigate IP spoofing.
"net.ipv4.conf.default.rp_filter" = 1;
"net.ipv4.conf.all.rp_filter" = 1;
# Do not accept IP source route packets (we're not a router)
"net.ipv4.conf.all.accept_source_route" = 0;
"net.ipv6.conf.all.accept_source_route" = 0;
# Don't send ICMP redirects (again, we're on a router)
"net.ipv4.conf.all.send_redirects" = 0;
"net.ipv4.conf.default.send_redirects" = 0;
# Refuse ICMP redirects (MITM mitigations)
"net.ipv4.conf.all.accept_redirects" = 0;
"net.ipv4.conf.default.accept_redirects" = 0;
"net.ipv4.conf.all.secure_redirects" = 0;
"net.ipv4.conf.default.secure_redirects" = 0;
"net.ipv6.conf.all.accept_redirects" = 0;
"net.ipv6.conf.default.accept_redirects" = 0;
# Protects against SYN flood attacks
"net.ipv4.tcp_syncookies" = 1;
# Incomplete protection again TIME-WAIT assassination
"net.ipv4.tcp_rfc1337" = 1;
## TCP optimization
# TCP Fast Open is a TCP extension that reduces network latency by packing
# data in the senders initial TCP SYN. Setting 3 = enable TCP Fast Open for
# both incoming and outgoing connections:
"net.ipv4.tcp_fastopen" = 3;
# Bufferbloat mitigations + slight improvement in throughput & latency
"net.ipv4.tcp_congestion_control" = "bbr";
"net.core.default_qdisc" = "cake";
## Allow rootless containers to get pinged and/or ping each other
"net.ipv4.ping_group_range" = "0 165536";
};
loader = {
timeout = 5;
systemd-boot = {
enable = true;
editor = false;
};
};
};
hardware.enableRedistributableFirmware = true;
}

View File

@ -1,37 +0,0 @@
{ config, pkgs, ... }:
{
imports = [ ./desktop-configuration.nix ];
# BSPWM on X11
services.xserver = {
displayManager = {
defaultSession = "none+bspwm";
};
windowManager = {
bspwm = {
enable = true;
configFile = "/home/pratham/.config/bspwm/bspwmrc";
sxhkd.configFile = "/home/pratham/.config/sxhkd/sxhkdrc";
};
};
};
environment.systemPackages = with pkgs; [
dunst
feh
jq
libnotify # provides notify-send
lxde.lxsession
picom
polybarFull
rofi
socat
wmctrl
xclip
xfce.thunar
xsecurelock
xsel
];
}

View File

@ -1,9 +0,0 @@
{ ... }:
{
boot = {
initrd.kernelModules = [ "amdgpu" ];
blacklistedKernelModules = [ "nvidia" ];
};
services.xserver.videoDrivers = [ "amdgpu" ];
}

View File

@ -1,9 +0,0 @@
{ ... }:
{
boot = {
initrd.kernelModules = [ "i915" ];
blacklistedKernelModules = [ "nvidia" ];
};
services.xserver.videoDrivers = [ "i915" ];
}

View File

@ -0,0 +1,19 @@
{ config
, lib
, pkgs
, nixpkgsRelease
, systemUser
, ...
}:
{
imports = [
../packages/user-packages.nix
../systemd-services/user-services.nix
./darwin.nix
./linux.nix
];
home.stateVersion = "${nixpkgsRelease}";
home.username = "${systemUser.username}";
}

View File

@ -0,0 +1,68 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
lib.mkIf pkgs.stdenv.isDarwin {
home.homeDirectory = "/Users/${systemUser.username}";
# TODO: install the following with brew
# alacritty
# bash
# homebrew/cask/mpv
# utm
# sourcing the bash completion offered by nixpkgs because macOS will not provide bash in the future
xdg.dataFile = {
"nix-bash/bash_completion.sh" = {
enable = true;
executable = true;
source = "${pkgs.bash-completion}/etc/profile.d/bash_completion.sh";
};
};
targets.darwin = {
currentHostDefaults = {
"com.apple.controlcenter".BatteryShowPercentage = true;
};
defaults = {
NSGlobalDomain = {
NSAutomaticCapitalizationEnabled = false;
NSAutomaticDashSubstitutionEnabled = false;
NSAutomaticPeriodSubstitutionEnabled = false;
NSAutomaticQuoteSubstitutionEnabled = false;
NSAutomaticSpellingCorrectionEnabled = false;
};
"com.apple.Safari" = {
AutoFillCreditCardData = false;
AutoFillPasswords = false;
AutoOpenSafeDownloads = false;
IncludeDevelopMenu = true;
ShowOverlayStatusBar = true;
};
"com.apple.desktopservices" = {
DSDontWriteNetworkStores = true;
DSDontWriteUSBStores = true;
};
"com.apple.dock" = {
expose-group-apps = false;
size-immutable = false;
tilesize = 32;
};
};
# https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/TextDefaultsBindings/TextDefaultsBindings.html
keybindings = {
"^\Uf702" = "moveWordLeft:"; # Ctrl-<Left>
"^\Uf703" = "moveWordRight:"; # Ctrl-<Right>
};
};
# home-manager does not need to overwrite these files
xdg.configFile = {};
home.file = {
".bash_profile".enable = false;
".bashrc".enable = false;
".profile".enable = false;
};
}

View File

@ -0,0 +1,11 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
lib.mkIf pkgs.stdenv.isLinux {
home.homeDirectory = "/home/${systemUser.username}";
targets.genericLinux.enable = true;
}

View File

@ -0,0 +1,94 @@
{ config
, lib
, pkgs
, nixpkgsRelease
, systemUser
, ...
}:
let
mkContainerService =
{ containerDescription
, containerName
, extraExecStart
, installServiceRequiredBy ? []
, unitAfter
, unitRequires ? []
, unitWants ? []
}:
{
Install = {
RequiredBy = installServiceRequiredBy;
WantedBy = [ "default.target" ];
};
Service = {
Environment = [ "PODMAN_SYSTEMD_UNIT=%n" ];
NotifyAccess = "all";
Restart = "always";
Type = "notify";
ExecStop = ''
${pkgs.podman}/bin/podman stop \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120
'';
ExecStopPost = ''
${pkgs.podman}/bin/podman rm \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120 \
--force
'';
ExecStart = ''
${pkgs.podman}/bin/podman run \
--cgroups no-conmon \
--cidfile %t/%n.ctr-id \
--detach \
--env TZ=Asia/Kolkata \
--label io.containers.autoupdate=registry \
--name ${containerName} \
--network containers_default \
--network-alias ${containerName} \
--pull missing \
--replace \
--rm \
--sdnotify conmon \
${extraExecStart}
'';
};
Unit = {
Description = "Container service for ${containerDescription}";
Documentation = [ "man:podman-run(1)" "man:podman-stop(1)" "man:podman-rm(1)" ];
Requires = unitRequires;
Wants = unitWants;
After = unitAfter;
RequiresMountsFor = [ "%t/containers" ];
};
};
in
{
home-manager.extraSpecialArgs = { inherit systemUser nixpkgsRelease; };
home-manager.users.${systemUser.username} = { config, lib, pkgs, ... }: {
imports = [
./common-home.nix
./virt-ovmf.nix
../systemd-services/podman/podman-init.nix
../systemd-services/podman/container-caddy-vishwambhar.nix
../systemd-services/podman/container-gitea-chitragupta.nix
../systemd-services/podman/container-gitea-govinda.nix
../systemd-services/podman/container-hugo-mahayogi.nix
../systemd-services/podman/container-hugo-vaikunthnatham.nix
../systemd-services/podman/container-transmission-raadhe.nix
../systemd-services/podman/container-uptime-vishnu.nix
];
_module.args = { inherit mkContainerService; };
};
}

View File

@ -0,0 +1,24 @@
{ config
, lib
, pkgs
, nixpkgsRelease
, systemUser
, ...
}:
{
imports = [ ./common-home.nix ];
nix = {
package = pkgs.nix;
checkConfig = true;
settings.experimental-features = [ "nix-command" "flakes" ];
};
news.display = "silent";
manual = {
html.enable = false;
json.enable = false;
manpages.enable = false; # no need to re-enable this, '--help' works
};
}

View File

@ -0,0 +1,56 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
lib.mkIf pkgs.stdenv.isLinux {
home.activation = {
OVMFActivation = lib.hm.dag.entryAfter [ "installPackages" ] ''
if [ "$(uname -m)" = 'aarch64' ]; then
EDKII_CODE_NIX="${pkgs.OVMF.fd}/FV/AAVMF_CODE.fd"
EDKII_VARS_NIX="${pkgs.OVMF.fd}/FV/AAVMF_VARS.fd"
elif [ "$(uname -m)" = 'x86_64' ]; then
EDKII_CODE_NIX="${pkgs.OVMF.fd}/FV/OVMF_CODE.fd"
EDKII_VARS_NIX="${pkgs.OVMF.fd}/FV/OVMF_VARS.fd"
fi
EDKII_DIR_HOME="/home/${systemUser.username}/.local/share/edk2"
EDKII_CODE_HOME="$EDKII_DIR_HOME/EDKII_CODE"
EDKII_VARS_HOME="$EDKII_DIR_HOME/EDKII_VARS"
if [ -d "$EDKII_DIR_HOME" ]; then
rm -rf "$EDKII_DIR_HOME"
fi
mkdir -vp "$EDKII_DIR_HOME"
cp "$EDKII_CODE_NIX" "$EDKII_CODE_HOME"
cp "$EDKII_VARS_NIX" "$EDKII_VARS_HOME"
chown $USER:$USER "$EDKII_CODE_HOME" "$EDKII_VARS_HOME"
chmod 644 "$EDKII_CODE_HOME" "$EDKII_VARS_HOME"
'';
};
# for libvirt, virt-manager, virsh
xdg.configFile = {
# from libvirt:qemu.conf
"libvirt/qemu.conf" = {
enable = true;
text = ''
nvram = [
"/home/${systemUser.username}/.local/share/edk2/EDKII_CODE:/home/${systemUser.username}/.local/share/edk2/EDKII_VARS",
"/run/libvirt/nix-ovmf/AAVMF_CODE.fd:/run/libvirt/nix-ovmf/AAVMF_VARS.fd",
"/run/libvirt/nix-ovmf/OVMF_CODE.fd:/run/libvirt/nix-ovmf/OVMF_VARS.fd"
]
'';
};
};
dconf.settings = {
"org/virt-manager/virt-manager/connections" = {
autoconnect = [ "qemu:///system" ];
uris = [ "qemu:///system" ];
};
};
}

View File

@ -0,0 +1,30 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
imports = [ ../../includes/display-server/kde-plasma.nix ];
fileSystems."/boot" = {
device = "/dev/disk/by-uuid/05DF-FC6E";
fsType = "vfat";
};
fileSystems."/" = {
device = "/dev/disk/by-uuid/3c7f4b5f-a96b-41c2-8934-457ac63b9122";
fsType = "xfs";
};
fileSystems."/home" = {
device = "/dev/disk/by-uuid/7e275e21-e939-4ef5-bbf7-011ed724655a";
fsType = "xfs";
};
fileSystems."/var" = {
device = "/dev/disk/by-uuid/6e310ca4-9af3-48e6-80cd-5f9d32b60eca";
fsType = "xfs";
};
}

View File

@ -0,0 +1,65 @@
{ config
, lib
, pkgs
, hostname
, forceLtsKernel ? false
, gatewayAddr
, hostId
, ipv4Address
, ipv4PrefixLength
, networkingIface
, supportedFilesystemsSansZFS
, system
, systemUser
, ...
}:
{
boot = {
kernelPackages = if forceLtsKernel
then pkgs.linuxPackages
else pkgs.linuxPackages_latest;
# no need to lib.mkForce because ZFS is only enabled in the ISO's config; nowhere else
supportedFilesystems = supportedFilesystemsSansZFS
++ (if forceLtsKernel
then [ "zfs" ]
else []);
zfs.forceImportAll = !forceLtsKernel;
};
zramSwap = {
enable = true;
algorithm = "zstd";
memoryPercent = 50;
};
networking = {
hostId = hostId;
hostName = hostname;
defaultGateway = {
address = gatewayAddr;
interface = networkingIface;
};
# use dhcp for the rest of the interfaces
useDHCP = lib.mkDefault true;
interfaces = {
"${networkingIface}" = {
# fuck the dhcp, we ball
useDHCP = lib.mkForce false;
ipv4.addresses = [{
address = ipv4Address;
prefixLength = ipv4PrefixLength;
}];
};
};
};
# this should actually be in ../configuration.nix
# but I don't have a way to pass in `system`
# without a **lot** of duplication in 'flake.nix'
nixpkgs.hostPlatform = system;
}

View File

@ -0,0 +1,30 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
imports = [ ../../includes/display-server/kde-plasma.nix ];
fileSystems."/boot" = {
device = "/dev/disk/by-uuid/B911-786F";
fsType = "vfat";
};
fileSystems."/" = {
device = "/dev/disk/by-uuid/83cf9d36-a97a-4336-ab3c-e818cc4edc30";
fsType = "xfs";
};
fileSystems."/home" = {
device = "/dev/disk/by-uuid/b8a89e3a-f6d9-456c-a554-6d6fd498ce46";
fsType = "xfs";
};
fileSystems."/var" = {
device = "/dev/disk/by-uuid/7cb3c69f-2c62-4498-86e5-f168b3f2daa4";
fsType = "xfs";
};
}

View File

@ -0,0 +1,28 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
fileSystems."/boot" = {
device = "/dev/disk/by-uuid/46BD-A6DC";
fsType = "vfat";
};
fileSystems."/" = {
device = "/dev/disk/by-uuid/d91a6ad1-bff4-43bd-bddd-2936a4f1078b";
fsType = "xfs";
};
fileSystems."/home" = {
device = "/dev/disk/by-uuid/a1e5cb2c-2863-4ee7-be1f-5b32f7eb9d16";
fsType = "xfs";
};
fileSystems."/var" = {
device = "/dev/disk/by-uuid/28cc2d02-e91b-4368-81e5-d65b9d8a50f3";
fsType = "xfs";
};
}

View File

@ -0,0 +1,43 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
fileSystems."/boot" = {
device = "/dev/disk/by-uuid/15D7-1EF4";
fsType = "vfat";
};
fileSystems."/" = {
device = "/dev/disk/by-uuid/c78f0691-a246-4b01-bb33-41662abcb2d6";
fsType = "xfs";
};
fileSystems."/home" = {
device = "/dev/disk/by-uuid/9f8f26e5-5fc3-4f4a-ae45-4f24151e846e";
fsType = "xfs";
};
fileSystems."/var" = {
device = "/dev/disk/by-uuid/cb9dcd35-891b-438f-baa1-fd3278dc3069";
fsType = "xfs";
};
networking.firewall.allowedTCPPorts = [
8001 # caddy HTTP
8002 # caddy HTTPS
8003 # personal blog
8004 # machine-setup/documentation blog
8005 # Gitea web UI
8006 # Gitea SSH
8008 # Uptime Kuma web UI
8009 # Transmission web UI
8010 # Transmission torrent comm port (TCP)
];
networking.firewall.allowedUDPPorts = [
9001 # Transmission torrent comm port (UDP)
];
}

View File

@ -0,0 +1,30 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
imports = [ ../../includes/display-server/bspwm.nix ];
fileSystems."/boot" = {
device = "/dev/disk/by-uuid/0659-9795";
fsType = "vfat";
};
fileSystems."/" = {
device = "/dev/disk/by-uuid/efea71e0-6154-4fb5-b10b-f84dec50c08f";
fsType = "xfs";
};
fileSystems."/home" = {
device = "/dev/disk/by-uuid/36ed9313-090d-4f24-995a-6c2c008e05fd";
fsType = "xfs";
};
fileSystems."/var" = {
device = "/dev/disk/by-uuid/1a989d9a-e9d6-4762-b6d4-8c4774ec1d93";
fsType = "xfs";
};
}

View File

@ -0,0 +1,28 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
fileSystems."/boot" = {
device = "/dev/disk/by-uuid/B4DF-D804";
fsType = "vfat";
};
fileSystems."/" = {
device = "/dev/disk/by-uuid/e3c37f3e-d920-4ec3-b80a-0ce53fabe98b";
fsType = "xfs";
};
fileSystems."/home" = {
device = "/dev/disk/by-uuid/df2f3866-9c7e-4f22-85ba-7f3ef3fe3e5c";
fsType = "xfs";
};
fileSystems."/var" = {
device = "/dev/disk/by-uuid/8507cc8d-8f9c-4360-b617-c628cd333bde";
fsType = "xfs";
};
}

View File

@ -0,0 +1,13 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
security.sudo.extraRules = [{
users = [ systemUser.username ];
commands = [{ command = "ALL"; options = [ "NOPASSWD" ]; }];
}];
}

View File

@ -0,0 +1,28 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
fileSystems."/boot" = {
device = "/dev/disk/by-uuid/D546-9873";
fsType = "vfat";
};
fileSystems."/" = {
device = "/dev/disk/by-uuid/4844363d-0dff-4dd2-88d8-704de750fe09";
fsType = "xfs";
};
fileSystems."/home" = {
device = "/dev/disk/by-uuid/6be45b33-103b-4679-b657-a8faeec3f8f6";
fsType = "xfs";
};
fileSystems."/var" = {
device = "/dev/disk/by-uuid/12fb6827-ac35-4400-ad9c-1763cd94e37f";
fsType = "xfs";
};
}

View File

@ -0,0 +1,28 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
fileSystems."/boot" = {
device = "/dev/disk/by-uuid/E150-2575";
fsType = "vfat";
};
fileSystems."/" = {
device = "/dev/disk/by-uuid/662384e7-4d66-4f9f-bf71-f6cb2eb20ad5";
fsType = "xfs";
};
fileSystems."/home" = {
device = "/dev/disk/by-uuid/f90fe2e2-23eb-4f96-800a-fc278fc3bc73";
fsType = "xfs";
};
fileSystems."/var" = {
device = "/dev/disk/by-uuid/58681bd6-8b77-437e-ad4b-af9cb052cc93";
fsType = "xfs";
};
}

View File

@ -1,11 +1,20 @@
{ config, pkgs, ... }:
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
# KDE Plasma 5 on Wayland
security.rtkit.enable = true;
sound.enable = true;
xdg.portal.enable = true;
services.xserver = {
enable = true;
layout = "us";
xkbVariant = "";
displayManager.hiddenUsers = [ "root" ];
desktopManager = {
wallpaper = {
@ -14,33 +23,28 @@
};
};
displayManager = {
hiddenUsers = [ "root" ];
sddm = {
videoDrivers = [
"amdgpu"
"xe"
];
};
services = {
printing.enable = true;
flatpak.enable = true;
pipewire = {
enable = true;
audio.enable = true;
pulse.enable = true;
alsa = {
enable = true;
enableHidpi = true;
#autologin = {
# enable = true;
# user = "pratham";
#};
support32Bit = true;
};
};
};
sound.enable = true;
security.rtkit.enable = true;
services.pipewire = {
enable = true;
audio.enable = true;
pulse.enable = true;
alsa = {
enable = true;
support32Bit = true;
};
};
services.printing.enable = true;
programs = {
firefox.enable = true;
light.enable = true;
@ -71,12 +75,4 @@
})
];
};
xdg.portal = {
enable = true;
configPackages = [ pkgs.libsForQt5.xdg-desktop-portal-kde ];
extraPortals = [ pkgs.libsForQt5.xdg-desktop-portal-kde ];
};
services.flatpak.enable = true;
}

View File

@ -0,0 +1,55 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
imports = [ ./base-display-server.nix ];
xdg.portal = {
configPackages = [ pkgs.libsForQt5.xdg-desktop-portal-kde ];
extraPortals = [ pkgs.libsForQt5.xdg-desktop-portal-kde ];
};
services.xserver = {
windowManager = {
bspwm = {
enable = true;
configFile = "/home/${systemUser.username}/.config/bspwm/bspwmrc";
sxhkd.configFile = "/home/${systemUser.username}/.config/sxhkd/sxhkdrc";
};
};
displayManager = {
defaultSession = "none+bspwm";
sddm = {
enable = true;
enableHidpi = true;
#autologin = {
# enable = true;
# user = systemUser.username;
#};
};
};
};
environment.systemPackages = with pkgs; [
dunst
feh
jq
libnotify # provides notify-send
lxde.lxsession
picom
polybarFull
rofi
socat
wmctrl
xclip
xfce.thunar
xsecurelock
xsel
];
}

View File

@ -1,23 +1,40 @@
{ config, pkgs, ... }:
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
imports = [ ./desktop-configuration.nix ];
imports = [ ./base-display-server.nix ];
xdg.portal = {
configPackages = [ pkgs.libsForQt5.xdg-desktop-portal-kde ];
extraPortals = [ pkgs.libsForQt5.xdg-desktop-portal-kde ];
};
# KDE Plasma 5 on Wayland
services.xserver = {
desktopManager = {
plasma5 = {
enable = true;
runUsingSystemd = true;
useQtScaling = true; # for HiDPI
bigscreen.enable = false; # enable this for HTPC
};
desktopManager.plasma5 = {
enable = true;
runUsingSystemd = true;
useQtScaling = true; # for HiDPI
bigscreen.enable = false; # enable this for HTPC
};
displayManager = {
defaultSession = "plasmawayland";
sddm = {
enable = true;
enableHidpi = true;
#autologin = {
# enable = true;
# user = systemUser.username;
#};
};
};
};
environment.systemPackages = with pkgs; [
cliphist
wayland-utils

View File

@ -1,10 +1,17 @@
{ config, lib, ... }:
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
nixpkgs.config.allowUnfreePredicate = pkg:
builtins.elem (lib.getName pkg) [
"nvidia-x11"
];
boot.blacklistedKernelModules = lib.mkForce [ "nvidia" ];
services.xserver.videoDrivers = lib.mkForce [ "nvidia" ];
nixpkgs.config.allowUnfreePredicate = pkg: builtins.elem (lib.getName pkg) [
"nvidia-x11"
];
hardware.opengl = {
enable = true;
@ -12,8 +19,6 @@
driSupport32Bit = true;
};
services.xserver.videoDrivers = [ "nvidia" ];
hardware.nvidia = {
modesetting.enable = true;
@ -22,7 +27,7 @@
powerManagement.finegrained = false; # turns off GPU when not in use
# the other OSS driver (**not "nouveau"**)
open = false; # TODO: try this out sometime
open = true; # TODO: try this out sometime
nvidiaSettings = true;

View File

@ -1,29 +0,0 @@
{ pkgs, ... }:
{
boot = {
supportedFilesystems = [ "zfs" ];
zfs.forceImportAll = true;
};
services.zfs = {
autoReplication.enable = false;
trim = {
enable = true;
interval = "Fri *-*-01..07 08:00:00";
};
autoScrub = {
enable = true;
interval = "Sat *-*-01..07 08:00:00";
pools = []; # empty list means all zpools
};
};
environment.systemPackages = with pkgs; [
linuxKernel.packages.linux_6_1.zfs
];
virtualisation.lxd.zfsSupport = true;
}

View File

@ -0,0 +1,86 @@
{ config
, lib
, pkgs
, ...
}:
let
userLocale = "en_IN";
envLocale = "${userLocale}.UTF-8";
in
{
time = {
timeZone = "Asia/Kolkata";
hardwareClockInLocalTime = true;
};
console = {
enable = true;
earlySetup = true;
};
i18n = {
defaultLocale = "${userLocale}";
extraLocaleSettings = {
LC_ADDRESS = "${userLocale}";
LC_IDENTIFICATION = "${userLocale}";
LC_MEASUREMENT = "${userLocale}";
LC_MONETARY = "${userLocale}";
LC_NAME = "${userLocale}";
LC_NUMERIC = "${userLocale}";
LC_PAPER = "${userLocale}";
LC_TELEPHONE = "${userLocale}";
LC_TIME = "${userLocale}";
};
};
environment = {
homeBinInPath = true;
localBinInPath = true;
variables = {
# for 'sudo -e'
EDITOR = "nvim";
VISUAL = "nvim";
# systemd
SYSTEMD_PAGER = "";
SYSTEMD_EDITOR = "nvim";
TERM = "xterm-256color";
# set locale manually because even though NixOS handles the 'en_IN' locale
# it doesn't append the string '.UTF-8' to LC_*
# but, UTF-8 **is supported**, so just go ahead and set it manually
LANG = lib.mkDefault "${envLocale}";
LC_ADDRESS = lib.mkDefault "${envLocale}";
LC_COLLATE = "${envLocale}";
LC_CTYPE = "${envLocale}";
LC_IDENTIFICATION = lib.mkDefault "${envLocale}";
LC_MEASUREMENT = lib.mkDefault "${envLocale}";
LC_MESSAGES = "${envLocale}";
LC_MONETARY = lib.mkDefault "${envLocale}";
LC_NAME = lib.mkDefault "${envLocale}";
LC_NUMERIC = lib.mkDefault "${envLocale}";
LC_PAPER = lib.mkDefault "${envLocale}";
LC_TELEPHONE = lib.mkDefault "${envLocale}";
LC_TIME = lib.mkDefault "${envLocale}";
LC_ALL = "";
# idk why, but some XDG vars aren't set, the missing ones are now set according to the
# spec: (https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html)
XDG_DATA_HOME = "$HOME/.local/share";
XDG_CONFIG_HOME = "$HOME/.config";
XDG_STATE_HOME = "$HOME/.local/state";
XDG_CACHE_HOME = "$HOME/.cache";
};
};
# yes, I want docs
documentation = {
enable = true;
dev.enable = true;
doc.enable = true;
info.enable = true;
man = {
enable = true;
generateCaches = true;
};
};
}

View File

@ -0,0 +1,38 @@
{ config
, lib
, pkgs
, ...
}:
let
domainNameServers = [
"1.1.1.1"
"1.0.0.1"
"8.8.8.8"
"8.8.4.4"
];
in
{
systemd.network = {
enable = true;
wait-online = {
enable = true;
anyInterface = true;
};
};
environment.etc."resolv.conf".mode = "direct-symlink";
services.resolved = {
enable = true;
fallbackDns = domainNameServers;
};
networking = {
firewall.enable = false; # this uses iptables AFAIK, use nftables instead
networkmanager.enable = true;
nftables.enable = true;
wireless.enable = false; # this enabled 'wpa_supplicant', use networkmanager instead
nameservers = domainNameServers;
};
}

View File

@ -0,0 +1,94 @@
{ config
, lib
, pkgs
, ...
}:
{
environment.systemPackages = with pkgs; [
# should be already included in the base image
#bzip2
#curl
#findutils
#gawk
#gnugrep
#gnused
#gnutar
#gzip
#iproute2
#iputils
#pinentry # pkg summary: GnuPGs interface to passphrase input
#procps # provides pgrep, kill, watch, ps, pidof, uptime, sysctl, free, etc
#rsync
#util-linux # provides blkid, losetup, lsblk, rfkill, fallocate, dmesg, etc
#zstd
# base system packages + packages what I *need*
hdparm
linux-firmware
pciutils # provides lspci and setpci
psmisc # provides killall, fuser, pslog, pstree, etc
pv
smartmontools
usbutils
vim # it is a necessity
parted
# optional, misc packages
cloud-utils # provides growpart
dmidecode
minisign
nvme-cli
# power management
acpi
lm_sensors
# virtualisation
qemu_kvm
# utilities specific to Nix
nix-output-monitor
nvd # diff between NixOS generations
];
programs = {
adb.enable = true;
bandwhich.enable = true;
ccache.enable = true;
command-not-found.enable = true;
dconf.enable = true;
git.enable = true;
gnupg.agent.enable = true;
htop.enable = true;
iotop.enable = true;
mtr.enable = true;
skim.fuzzyCompletion = true;
sniffnet.enable = true;
tmux.enable = true;
traceroute.enable = true;
trippy.enable = true;
usbtop.enable = true;
bash = {
enableCompletion = true;
# notifications when long-running terminal commands complete
undistractMe = {
enable = true;
playSound = true;
timeout = 300; # notify only if said command has been running for this many seconds
};
# aliases for the root user
# doesn't affect 'pratham' since there is an `unalias -a` in $HOME/.bashrc
shellAliases = {
"e" = "${pkgs.vim}/bin/vim";
};
};
nano = {
enable = true;
syntaxHighlight = true;
};
};
}

View File

@ -0,0 +1,147 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
let
packagesInPathForAerc = with pkgs; [ bat catimg pandoc ];
aercFull = pkgs.aerc.overrideAttrs (final: prev: {
nativeBuildInputs = prev.nativeBuildInputs or [] ++ (with pkgs; [ makeWrapper ]);
postInstall = (prev.postInstall or "") + ''
wrapProgram $out/bin/aerc \
--prefix PATH : ${pkgs.lib.makeBinPath packagesInPathForAerc}
'';
});
linuxPackages = lib.optionals (pkgs.stdenv.isLinux) (with pkgs; [
cargo-valgrind
inotify-tools
rpm
thunderbird
ventoy
wol
]);
darwinPackages = lib.optionals (pkgs.stdenv.isDarwin) (with pkgs; [
coreutils-prefixed
gawk
gnugrep
gnused
tmux
watch
(nerdfonts.override {
fonts = [
"FiraCode"
"Overpass"
"SourceCodePro"
];
})
]);
in
{
home.packages = linuxPackages ++ darwinPackages ++ (with pkgs; [
# programming tools + compilers
#cargo-deb # generate .deb packages solely based on Cargo.toml
#cargo-ndk # extension for building Android NDK projects
b4 # applying patches from mailing lists
cargo-audit # audit crates for security vulnerabilities
cargo-benchcmp # compare Rust micro-benchmarks
cargo-binstall # install Rust binaries instead of building them from src
cargo-bisect-rustc # find exactly which rustc commit/release-version which prevents your code from building now
cargo-bloat # find what takes the most space in the executable
cargo-cache # manage cargo cache (${CARGO_HOME}); print and remove dirs selectively
cargo-chef # for speeding up container builds using layer caching
cargo-deps # build dependency graph of Rust projects
cargo-dist # distribute on crates.io
cargo-flamegraph # flamegraphs without Perl or pipes
cargo-hack # build project with all the possible variations of options/flags and check which ones fail and/or succeed
cargo-outdated # show outdated deps
cargo-profiler # profile Rust binaries
cargo-public-api # detect breaking API changes and semver violations
cargo-show-asm # display ASM, LLVM-IR, MIR and WASM for the Rust src
cargo-sweep # cleanup unused build files
cargo-udeps # find unused dependencies
cargo-update # update installed binaries
cargo-vet # ensure that the third-party dependencies are audited by a trusted source
cargo-watch # run cargo commands when the src changes
rustup # provides rustfmt, cargo-clippy, rustup, cargo, rust-lldb, rust-analyzer, rustc, rust-gdb, cargo-fmt
# e-mail
aercFull
protonmail-bridge
# misc utilities + shells
asciinema
buildah
choose
dash
dict
dig # provides dig and nslookup
dpkg
du-dust
dua
fd
ffmpeg
file
fzf
hyperfine
imagemagick
iperf # this is iperf3
iperf2 # this is what is usually 'iperf' on other distros
mediainfo
nload
parallel
picocom
procs
python3Minimal
sd
tre-command
tree
unzip
wget
zip
# utilities specific to Nix
nix-prefetch
nix-prefetch-git
nix-prefetch-github
]);
programs = {
aria2.enable = true;
bat.enable = true;
bottom.enable = true;
broot.enable = true;
btop.enable = true;
ripgrep.enable = true;
tealdeer.enable = true;
yt-dlp.enable = true;
zoxide.enable = true;
direnv = {
enable = true;
enableBashIntegration = true;
nix-direnv.enable = true;
};
neovim = {
enable = true;
extraPackages = with pkgs; [
clang-tools # provides clangd
gcc # for nvim-tree's parsers
lldb # provides lldb-vscode
lua-language-server
nil # language server for Nix
nixpkgs-fmt
nodePackages.bash-language-server
ruff
shellcheck
tree-sitter # otherwise nvim complains that the binary 'tree-sitter' is not found
];
};
};
}

View File

@ -0,0 +1,66 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
let
flakeUri = "/root/prathams-nixos";
in
{
system.autoUpgrade = {
enable = true;
allowReboot = false;
dates = "daily"; # *-*-* 00:00:00
flake = flakeUri;
operation = "boot";
persistent = false;
};
systemd = {
timers."update-nixos-config" = {
enable = true;
requiredBy = [ "timers.target" ];
timerConfig = {
Unit = "update-nixos-config";
OnBootSec = "10m";
OnCalendar = "hourly";
};
};
services."update-nixos-config" = {
enable = true;
path = with pkgs; [
gitMinimal
nettools
nix
];
requires = [ "network-online.target" ];
before = [ "nixos-upgrade.service" ];
requiredBy = [ "nixos-upgrade.service" ];
serviceConfig = {
User = "root";
Type = "oneshot";
};
script = ''
set -xeuf -o pipefail
[[ ! -d ${flakeUri} ]] && git clone https://gitlab.com/thefossguy/prathams-nixos ${flakeUri}
pushd ${flakeUri}
git restore flake.lock
git pull
nix flake update
nix build --print-build-logs --show-trace .#machines."$(hostname)"
popd
'';
};
};
}

View File

@ -0,0 +1,36 @@
{ config
, lib
, pkgs
, osConfig
, systemUser
, mkContainerService
, ...
}:
let
containerImage = "docker.io/library/caddy:latest";
containerVolumePath = "/home/${systemUser.username}/container-data/volumes/caddy";
containerDescription = "Caddy Web Server (reverse proxy)";
containerName = "caddy-vishwambhar";
unitAfter = [ "podman-init.service" ];
unitRequires = [ "podman-init.service" ];
extraExecStart = ''
--publish 8001:80 \
--publish 8002:443 \
--volume ${containerVolumePath}/caddy_config:/config:U \
--volume ${containerVolumePath}/caddy_data:/data:U \
--volume ${containerVolumePath}/Caddyfile:/etc/caddy/Caddyfile:U \
--volume ${containerVolumePath}/site:/srv:U \
--volume ${containerVolumePath}/ssl:/etc/ssl:U \
${containerImage} \
caddy run --config /etc/caddy/Caddyfile
'';
in
lib.mkIf (osConfig.networking.hostName == "reddish") {
systemd.user.services."container-${containerName}" = mkContainerService {
inherit containerDescription containerName extraExecStart unitAfter unitRequires;
};
}

View File

@ -0,0 +1,34 @@
{ config
, lib
, pkgs
, osConfig
, systemUser
, mkContainerService
, ...
}:
let
containerImage = "docker.io/library/postgres:15-bookworm";
containerVolumePath = "/home/${systemUser.username}/container-data/volumes/gitea/database";
containerDescription = "Gitea database (PostgreSQL)";
containerName = "gitea-chitragupta";
unitAfter = [ "podman-init.service" ];
unitRequires = [ "podman-init.service" ];
installServiceRequiredBy = [ "container-gitea-govinda.service" ];
extraExecStart = ''
--env POSTGRES_USER=gitea \
--env POSTGRES_PASSWORD=/run/secrets/gitea_database_user_password \
--env POSTGRES_DB=gitea \
--secret gitea_database_user_password \
--volume ${containerVolumePath}:/var/lib/postgresql/data:U \
${containerImage}
'';
in
lib.mkIf (osConfig.networking.hostName == "reddish") {
systemd.user.services."container-${containerName}" = mkContainerService {
inherit containerDescription containerName extraExecStart unitAfter unitRequires installServiceRequiredBy;
};
}

View File

@ -0,0 +1,60 @@
{ config
, lib
, pkgs
, osConfig
, systemUser
, mkContainerService
, ...
}:
let
containerImage = "docker.io/gitea/gitea:latest";
containerVolumePath = "/home/${systemUser.username}/container-data/volumes/gitea";
containerDescription = "Gitea web UI";
containerName = "gitea-govinda";
unitAfter = unitRequires ++ unitWants;
unitRequires = [ "container-gitea-chitragupta.service" ];
unitWants = [ "container-caddy-vishwambhar.service" ];
extraExecStart = ''
--env GITEA__actions__ENABLED=false \
--env GITEA__cron__ENABLED=true \
--env GITEA__cron__RUN_AT_START=true \
--env GITEA__database__DB_TYPE=postgres \
--env GITEA__database__HOST=gitea-chitragupta:5432 \
--env GITEA__database__NAME=gitea \
--env GITEA__database__PASSWD=/run/secrets/gitea_database_user_password \
--env GITEA__database__USER=gitea \
--env GITEA__openid__ENABLE_OPENID_SIGNIN=false \
--env GITEA__openid__ENABLE_OPENID_SIGNUP=false \
--env GITEA__repository__DEFAULT_BRANCH=master \
--env GITEA__repository__DEFAULT_PRIVATE=public \
--env GITEA__repository__DEFAULT_PUSH_CREATE_PRIVATE=false \
--env GITEA__repository__DEFAULT_REPO_UNITS="repo.code,repo.releases" \
--env GITEA__RUN_MODE=prod \
--env GITEA__security__LOGIN_REMEMBER_DAYS=14 \
--env GITEA__server__DISABLE_SSH=false \
--env GITEA__server__DOMAIN=git.thefossguy.com \
--env GITEA__server__ROOT_URL=https://git.thefossguy.com \
--env GITEA__server__SSH_DOMAIN=git.thefossguy.com \
--env GITEA__server__SSH_EXPOSE_ANONYMOUS=true \
--env GITEA__server__SSH_LISTEN_PORT=3001 \
--env GITEA__server__SSH_PORT=22 \
--env GITEA__server__START_SSH_SERVER=true \
--env GITEA__service__DEFAULT_KEEP_EMAIL_PRIVATE=true \
--env GITEA__service__DISABLE_REGISTRATION=true \
--secret gitea_database_user_password \
--publish 8005:3000 \
--publish 8006:3001 \
--volume ${containerVolumePath}/web:/data:U \
--volume ${containerVolumePath}/ssh:/data/git/.ssh:U \
${containerImage}
'';
in
lib.mkIf (osConfig.networking.hostName == "reddish") {
systemd.user.services."container-${containerName}" = mkContainerService {
inherit containerDescription containerName extraExecStart unitAfter unitRequires unitWants;
};
}

View File

@ -0,0 +1,31 @@
{ config
, lib
, pkgs
, osConfig
, systemUser
, mkContainerService
, ...
}:
let
containerImage = "docker.io/klakegg/hugo:ext-debian";
containerVolumePath = "/home/${systemUser.username}/container-data/volumes/mach";
containerDescription = "Pratham Patel's documentation website";
containerName = "hugo-mahayogi";
unitAfter = [ "container-caddy-vishwambhar.service" ];
unitWants = [ "container-caddy-vishwambhar.service" ];
extraExecStart = ''
--publish 8004:1313 \
--volume ${containerVolumePath}:/src:U \
${containerImage} \
server --disableFastRender --baseURL https://mach.thefossguy.com/ --appendPort=false --port=1313
'';
in
lib.mkIf (osConfig.networking.hostName == "reddish") {
systemd.user.services."container-${containerName}" = mkContainerService {
inherit containerDescription containerName extraExecStart unitAfter unitWants;
};
}

View File

@ -0,0 +1,31 @@
{ config
, lib
, pkgs
, osConfig
, systemUser
, mkContainerService
, ...
}:
let
containerImage = "docker.io/klakegg/hugo:ext-debian";
containerVolumePath = "/home/${systemUser.username}/container-data/volumes/blog";
containerDescription = "Pratham Patel's personal blog";
containerName = "hugo-vaikunthnatham";
unitAfter = [ "container-caddy-vishwambhar.service" ];
unitWants = [ "container-caddy-vishwambhar.service" ];
extraExecStart = ''
--publish 8003:1313 \
--volume ${containerVolumePath}:/src:U \
${containerImage} \
server --disableFastRender --baseURL https://blog.thefossguy.com/ --appendPort=false --port=1313
'';
in
lib.mkIf (osConfig.networking.hostName == "reddish") {
systemd.user.services."container-${containerName}" = mkContainerService {
inherit containerDescription containerName extraExecStart unitAfter unitWants;
};
}

View File

@ -0,0 +1,32 @@
{ config
, lib
, pkgs
, osConfig
, mkContainerService
, ...
}:
let
containerImage = "lscr.io/linuxserver/transmission:latest";
containerVolumePath = "/trayimurti/torrents";
containerDescription = "Transmission BitTorrent client";
containerName = "transmission-raadhe";
unitAfter = [ "container-caddy-vishwambhar.service" ];
unitWants = [ "container-caddy-vishwambhar.service" ];
extraExecStart = ''
--publish 8009:9091 \
--publish 8010:5143 \
--publish 9001:5143/udp \
--volume ${containerVolumePath}/downloads:/downloads:U \
--volume ${containerVolumePath}/config:/config:U \
${containerImage}
'';
in
lib.mkIf (osConfig.networking.hostName == "reddish") {
systemd.user.services."container-${containerName}" = mkContainerService {
inherit containerDescription containerName extraExecStart unitAfter unitWants;
};
}

View File

@ -0,0 +1,30 @@
{ config
, lib
, pkgs
, osConfig
, systemUser
, mkContainerService
, ...
}:
let
containerImage = "docker.io/louislam/uptime-kuma:debian";
containerVolumePath = "/home/${systemUser.username}/container-data/volumes/uptimekuma";
containerDescription = "Uptime Kuma";
containerName = "uptime-vishnu";
unitAfter = [ "container-caddy-vishwambhar.service" ];
unitWants = [ "container-caddy-vishwambhar.service" ];
extraExecStart = ''
--publish 8008:3001 \
--volume ${containerVolumePath}:/app/data:U \
${containerImage}
'';
in
lib.mkIf (osConfig.networking.hostName == "reddish") {
systemd.user.services."container-${containerName}" = mkContainerService {
inherit containerDescription containerName extraExecStart unitAfter unitWants;
};
}

View File

@ -0,0 +1,42 @@
{ config
, lib
, pkgs
, osConfig
, systemUser
, ...
}:
lib.mkIf (osConfig.networking.hostName == "reddish") {
systemd.user.services = {
"podman-init" = {
Unit = {
Description = "Podman initialization";
Requires = [ "podman-restart.service" ];
After = [ "podman-restart.service" ];
Documentation = [
"man:openssl-create(1)"
"man:podman-network-create(1)"
"man:podman-network-exists(1)"
"man:podman-secret-create(1)"
"man:podman-secret-exists(1)"
];
};
Service = {
ExecStart = "${pkgs.nix}/bin/nix-shell /home/${systemUser.username}/.local/scripts/other-common-scripts/podman-initialization.sh";
Type = "oneshot";
};
Install = {
WantedBy = [ "default.target" ];
};
};
};
home.packages = with pkgs; [
ctop
podman-compose
podman-tui
];
}

View File

@ -0,0 +1,60 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
let
userHome = "/home/${systemUser.username}";
in
{
imports = [ ./nixos-update-and-upgrade.nix ];
services = {
fwupd.enable = true;
journald.storage = "persistent";
logrotate.enable = true;
timesyncd.enable = true; # NTP
udisks2.enable = true;
locate = {
enable = true;
interval = "hourly";
localuser = null;
package = pkgs.mlocate;
pruneBindMounts = true;
prunePaths = [
"${userHome}/.cache"
"${userHome}/.dotfiles"
"${userHome}/.local/share"
"${userHome}/.local/state"
"${userHome}/.nix-defexpr"
"${userHome}/.nix-profile"
"${userHome}/.nvim/undodir"
"${userHome}/.rustup"
"${userHome}/.vms"
"${userHome}/.zkbd"
"/nix"
];
};
# sshd_config
openssh = {
enable = true;
ports = [ 22 ];
openFirewall = true;
settings = {
Protocol = 2;
MaxAuthTries = 2;
PermitEmptyPasswords = lib.mkForce false;
PasswordAuthentication = lib.mkForce false;
PermitRootLogin = lib.mkForce "prohibit-password";
X11Forwarding = false;
};
};
};
}

View File

@ -0,0 +1,70 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
let
scriptsDir = "/home/${systemUser.username}/.local/scripts";
in
lib.mkIf pkgs.stdenv.isLinux {
systemd.user.services = {
"dotfiles-pull" = {
Service = {
ExecStart = "${pkgs.dash}/bin/dash ${scriptsDir}/other-common-scripts/dotfiles-pull.sh";
Environment = [ ''"PATH=${pkgs.git}/bin:${pkgs.openssh}/bin"'' ];
Type = "oneshot";
};
Install = { WantedBy = [ "default.target" ]; };
};
"flatpak-manage" = {
Service = {
ExecStart = "${pkgs.bash}/bin/bash ${scriptsDir}/other-common-scripts/flatpak-manage.sh";
Environment = [ ''"PATH=${pkgs.gnugrep}/bin"'' ];
Type = "oneshot";
};
Install = { WantedBy = [ "default.target" ]; };
};
"update-rust" = {
Service = {
ExecStart = "${pkgs.dash}/bin/dash ${scriptsDir}/other-common-scripts/rust-manage.sh";
Environment = [ ''"PATH=${pkgs.procps}/bin:${pkgs.rustup}/bin"'' ];
Type = "oneshot";
};
Install = { WantedBy = [ "default.target" ]; };
};
};
systemd.user.timers = {
"dotfiles-pull" = {
Timer = {
OnBootSec = "now";
OnCalendar = "*-*-* 23:00:00";
Unit = "dotfiles-pull.service";
};
Install = { WantedBy = [ "timers.target" ]; };
};
"flatpak-manage" = {
Timer = {
OnBootSec = "now";
OnCalendar = "*-*-* 04:00:00";
Unit = "flatpak-manage.service";
};
Install = { WantedBy = [ "timers.target" ]; };
};
"update-rust" = {
Timer = {
OnBootSec = "now";
OnCalendar = "*-*-* 04:00:00";
Unit = "update-rust.service";
};
Install = { WantedBy = [ "timers.target" ]; };
};
};
}

View File

@ -0,0 +1,98 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
let
sudoRules = with pkgs; [
{ package = coreutils; command = "sync"; }
{ package = hdparm; command = "hdparm"; }
{ package = nix; command = "nix-collect-garbage"; }
{ package = nixos-rebuild; command = "nixos-rebuild"; }
{ package = nvme-cli; command = "nvme"; }
{ package = systemd; command = "poweroff"; }
{ package = systemd; command = "reboot"; }
{ package = systemd; command = "shutdown"; }
{ package = systemd; command = "systemctl"; }
{ package = util-linux; command = "dmesg"; }
];
mkSudoRule = rule: {
command = "${rule.package}/bin/${rule.command}";
options = [ "NOPASSWD" ];
};
sudoCommands = map mkSudoRule sudoRules;
in
{
users = {
allowNoPasswordLogin = false;
defaultUserShell = pkgs.bash;
enforceIdUniqueness = true;
mutableUsers = false; # setting this to `false` means users/groups cannot be added with `useradd`/`groupadd`
groups.${systemUser.username} = {
name = "${systemUser.username}";
gid = 1000;
};
users.${systemUser.username} = {
createHome = true;
description = "${systemUser.fullname}";
group = "${systemUser.username}";
hashedPassword = "${systemUser.hashedPassword}";
home = "/home/${systemUser.username}";
isNormalUser = true; # normal vs system is really about a "real" vs "builder" user, respectively
isSystemUser = false;
linger = systemUser.enableLingering or false;
subGidRanges = [{ startGid = 10000; count = 65536; }];
subUidRanges = [{ startUid = 10000; count = 65536; }];
uid = 1000;
useDefaultShell = true;
extraGroups = [
"adbusers"
"adm"
"dialout"
"ftp"
"games"
"http"
"kvm"
"libvirt"
"libvirtd"
"log"
"mlocate"
"networkmanager"
"podman"
"qemu-libvirtd"
"rfkill"
"sshusers"
"sys"
"systemd-journal"
"uucp"
"video"
"wheel"
"zfs-read"
];
};
};
security = {
polkit.enable = true;
sudo = {
enable = true;
execWheelOnly = true;
keepTerminfo = true;
wheelNeedsPassword = true;
extraRules = [{
users = [ "${systemUser.username}" ];
commands = sudoCommands;
}];
};
};
}

View File

@ -1,44 +0,0 @@
{ pkgs, ... }:
{
home-manager.users.pratham = { pkgs, ... }: {
systemd.user.services = {
"podman-init" = {
Unit = {
Description = "Podman initialization";
Documentation = [
"man:podman-secret-exists(1)"
"man:podman-secret-create(1)"
"man:openssl-create(1)"
"man:podman-network-exists(1)"
"man:podman-network-create(1)"
];
Requires = [ "podman-restart.service" ];
After = [ "podman-restart.service" ];
};
Service = {
ExecStart = "${pkgs.nix}/bin/nix-shell /home/pratham/.local/scripts/other-common-scripts/podman-initialization.sh";
Type = "oneshot";
};
Install = {
WantedBy = [ "default.target" ];
};
};
};
};
environment.systemPackages = with pkgs; [
ctop
podman-compose
podman-tui
];
imports = [
./services/podman-gitea-chitragupta.nix
./services/podman-gitea-govinda.nix
./services/podman-hugo-mahayogi.nix
./services/podman-hugo-vaikunthnatham.nix
./services/podman-transmission-raadhe.nix
./services/podman-uptime-vishnu.nix
];
}

View File

@ -1,78 +0,0 @@
{ ... }:
{
home-manager.users.pratham = { pkgs, ... }: {
systemd.user.services =
let
container_name = "caddy-vishwambhar";
container_image = "docker.io/library/caddy:latest";
container_volume_path = "/home/pratham/container-data/volumes/caddy";
exec_start = ''
${pkgs.podman}/bin/podman run \
--cgroups no-conmon \
--cidfile %t/%n.ctr-id \
--detach \
--env TZ=Asia/Kolkata \
--label io.containers.autoupdate=registry \
--name ${container_name} \
--network containers_default \
--network-alias ${container_name} \
--pull missing \
--replace \
--rm \
--sdnotify conmon'';
exec_stop = ''
${pkgs.podman}/bin/podman stop \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120
'';
exec_stop_post = ''
${pkgs.podman}/bin/podman rm \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120 \
--force
'';
in
{
"container-${container_name}" = {
Unit = {
Description = "Container service for Caddy Web Server (reverse proxy)";
Documentation = [ "man:podman-run(1)" "man:podman-stop(1)" "man:podman-rm(1)" ];
Requires = [ "podman-init.service" ];
After = [ "podman-init.service" ];
RequiresMountsFor = [ "%t/containers" ];
};
Service = {
ExecStart = ''
${exec_start} \
--publish 8001:80 \
--publish 8002:443 \
--volume ${container_volume_path}/caddy_config:/config:U \
--volume ${container_volume_path}/caddy_data:/data:U \
--volume ${container_volume_path}/Caddyfile:/etc/caddy/Caddyfile:U \
--volume ${container_volume_path}/site:/srv:U \
--volume ${container_volume_path}/ssl:/etc/ssl:U \
${container_image} \
caddy run --config /etc/caddy/Caddyfile
'';
ExecStop = "${exec_stop}";
ExecStopPost = "${exec_stop_post}";
Environment = [ "PODMAN_SYSTEMD_UNIT=%n" ];
Type = "notify";
NotifyAccess = "all";
Restart = "always";
};
Install = {
WantedBy = [ "default.target" ];
};
};
};
};
networking.firewall.allowedTCPPorts = [
8001 # caddy HTTP
8002 # caddy HTTPS
];
}

View File

@ -1,71 +0,0 @@
{ ... }:
{
home-manager.users.pratham = { pkgs, ... }: {
systemd.user.services =
let
container_name = "gitea-chitragupta";
container_image = "docker.io/library/postgres:15-bookworm";
container_volume_path = "/home/pratham/container-data/volumes/gitea/database";
exec_start = ''
${pkgs.podman}/bin/podman run \
--cgroups no-conmon \
--cidfile %t/%n.ctr-id \
--detach \
--env TZ=Asia/Kolkata \
--label io.containers.autoupdate=registry \
--name ${container_name} \
--network containers_default \
--network-alias ${container_name} \
--pull missing \
--replace \
--rm \
--sdnotify conmon'';
exec_stop = ''
${pkgs.podman}/bin/podman stop \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120
'';
exec_stop_post = ''
${pkgs.podman}/bin/podman rm \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120 \
--force
'';
in
{
"container-${container_name}" = {
Unit = {
Description = "Container service for Gitea database (PostgreSQL)";
Documentation = [ "man:podman-run(1)" "man:podman-stop(1)" "man:podman-rm(1)" ];
Requires = [ "podman-init.service" ];
After = [ "podman-init.service" ];
RequiresMountsFor = [ "%t/containers" ];
};
Service = {
ExecStart = ''
${exec_start} \
--env POSTGRES_USER=gitea \
--env POSTGRES_PASSWORD=/run/secrets/gitea_database_user_password \
--env POSTGRES_DB=gitea \
--secret gitea_database_user_password \
--volume ${container_volume_path}:/var/lib/postgresql/data:U \
${container_image}
'';
ExecStop = "${exec_stop}";
ExecStopPost = "${exec_stop_post}";
Environment = [ "PODMAN_SYSTEMD_UNIT=%n" ];
Type = "notify";
NotifyAccess = "all";
Restart = "always";
};
Install = {
RequiredBy = [ "container-gitea-govinda.service" ];
WantedBy = [ "default.target" ];
};
};
};
};
}

View File

@ -1,108 +0,0 @@
{ ... }:
{
home-manager.users.pratham = { pkgs, ... }: {
systemd.user.services =
let
container_name = "gitea-govinda";
container_image = "docker.io/gitea/gitea:latest";
container_volume_path = "/home/pratham/container-data/volumes/gitea";
db_container_service = "container-gitea-chitragupta.service";
exec_start = ''
${pkgs.podman}/bin/podman run \
--cgroups no-conmon \
--cidfile %t/%n.ctr-id \
--detach \
--env TZ=Asia/Kolkata \
--label io.containers.autoupdate=registry \
--name ${container_name} \
--network containers_default \
--network-alias ${container_name} \
--pull missing \
--replace \
--rm \
--sdnotify conmon'';
exec_stop = ''
${pkgs.podman}/bin/podman stop \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120
'';
exec_stop_post = ''
${pkgs.podman}/bin/podman rm \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120 \
--force
'';
in
{
"container-${container_name}" = {
Unit = {
Description = "Container service for Gitea web UI";
Documentation = [ "man:podman-run(1)" "man:podman-stop(1)" "man:podman-rm(1)" ];
Requires = [ "${db_container_service}" ];
Wants = [ "container-caddy-vishwambhar.service" ];
After = [ "${db_container_service}" "container-caddy-vishwambhar.service" ];
RequiresMountsFor = [ "%t/containers" ];
};
Service = {
ExecStart = ''
${exec_start} \
--env GITEA__actions__ENABLED=false \
--env GITEA__cron__ENABLED=true \
--env GITEA__cron__RUN_AT_START=true \
--env GITEA__database__DB_TYPE=postgres \
--env GITEA__database__HOST=gitea-chitragupta:5432 \
--env GITEA__database__NAME=gitea \
--env GITEA__database__PASSWD=/run/secrets/gitea_database_user_password \
--env GITEA__database__USER=gitea \
--env GITEA__openid__ENABLE_OPENID_SIGNIN=false \
--env GITEA__openid__ENABLE_OPENID_SIGNUP=false \
--env GITEA__repository__DEFAULT_BRANCH=master \
--env GITEA__repository__DEFAULT_PRIVATE=public \
--env GITEA__repository__DEFAULT_PUSH_CREATE_PRIVATE=false \
--env GITEA__repository__DEFAULT_REPO_UNITS="repo.code,repo.releases" \
--env GITEA__RUN_MODE=prod \
--env GITEA__security__LOGIN_REMEMBER_DAYS=14 \
--env GITEA__server__DISABLE_SSH=false \
--env GITEA__server__DOMAIN=git.thefossguy.com \
--env GITEA__server__ROOT_URL=https://git.thefossguy.com \
--env GITEA__server__SSH_DOMAIN=git.thefossguy.com \
--env GITEA__server__SSH_EXPOSE_ANONYMOUS=true \
--env GITEA__server__SSH_LISTEN_PORT=3001 \
--env GITEA__server__SSH_PORT=22 \
--env GITEA__server__START_SSH_SERVER=true \
--env GITEA__service__DEFAULT_KEEP_EMAIL_PRIVATE=true \
--env GITEA__service__DISABLE_REGISTRATION=true \
--secret gitea_database_user_password \
--publish 8005:3000 \
--publish 8006:3001 \
--volume ${container_volume_path}/web:/data:U \
--volume ${container_volume_path}/ssh:/data/git/.ssh:U \
${container_image}
'';
ExecStop = "${exec_stop}";
ExecStopPost = "${exec_stop_post}";
Environment = [ "PODMAN_SYSTEMD_UNIT=%n" ];
Type = "notify";
NotifyAccess = "all";
Restart = "always";
};
Install = {
WantedBy = [ "default.target" ];
};
};
};
};
networking.firewall.allowedTCPPorts = [
8005 # Gitea web UI
8006 # Gitea SSH
];
imports = [
./podman-caddy-vishwambhar.nix
./podman-gitea-chitragupta.nix
];
}

View File

@ -1,77 +0,0 @@
{ ... }:
{
home-manager.users.pratham = { pkgs, ... }: {
systemd.user.services =
let
container_name = "hugo-mahayogi";
container_image = "docker.io/klakegg/hugo:ext-debian";
container_volume_path = "/home/pratham/container-data/volumes/mach";
exec_start = ''
${pkgs.podman}/bin/podman run \
--cgroups no-conmon \
--cidfile %t/%n.ctr-id \
--detach \
--env TZ=Asia/Kolkata \
--label io.containers.autoupdate=registry \
--name ${container_name} \
--network containers_default \
--network-alias ${container_name} \
--pull missing \
--replace \
--rm \
--sdnotify conmon'';
exec_stop = ''
${pkgs.podman}/bin/podman stop \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120
'';
exec_stop_post = ''
${pkgs.podman}/bin/podman rm \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120 \
--force && \
rm -rf ${container_volume_path}/resources
'';
in
{
"container-${container_name}" = {
Unit = {
Description = "Container service for Pratham Patel's documentation website";
Documentation = [ "man:podman-run(1)" "man:podman-stop(1)" "man:podman-rm(1)" ];
Wants = [ "container-caddy-vishwambhar.service" ];
After = [ "container-caddy-vishwambhar.service" ];
RequiresMountsFor = [ "%t/containers" ];
};
Service = {
ExecStart = ''
${exec_start} \
--publish 8004:1313 \
--volume ${container_volume_path}:/src:U \
${container_image} \
server --disableFastRender --baseURL https://mach.thefossguy.com/ --appendPort=false --port=1313
'';
ExecStop = "${exec_stop}";
ExecStopPost = "${exec_stop_post}";
Environment = [ "PODMAN_SYSTEMD_UNIT=%n" ];
Type = "notify";
NotifyAccess = "all";
Restart = "always";
};
Install = {
WantedBy = [ "default.target" ];
};
};
};
};
networking.firewall.allowedTCPPorts = [
8004 # machine-setup/documentation blog
];
imports = [
./podman-caddy-vishwambhar.nix
];
}

View File

@ -1,77 +0,0 @@
{ ... }:
{
home-manager.users.pratham = { pkgs, ... }: {
systemd.user.services =
let
container_name = "hugo-vaikunthnatham";
container_image = "docker.io/klakegg/hugo:ext-debian";
container_volume_path = "/home/pratham/container-data/volumes/blog";
exec_start = ''
${pkgs.podman}/bin/podman run \
--cgroups no-conmon \
--cidfile %t/%n.ctr-id \
--detach \
--env TZ=Asia/Kolkata \
--label io.containers.autoupdate=registry \
--name ${container_name} \
--network containers_default \
--network-alias ${container_name} \
--pull missing \
--replace \
--rm \
--sdnotify conmon'';
exec_stop = ''
${pkgs.podman}/bin/podman stop \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120
'';
exec_stop_post = ''
${pkgs.podman}/bin/podman rm \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120 \
--force && \
rm -rf ${container_volume_path}/resources
'';
in
{
"container-${container_name}" = {
Unit = {
Description = "Container service for Pratham Patel's personal blog";
Documentation = [ "man:podman-run(1)" "man:podman-stop(1)" "man:podman-rm(1)" ];
Wants = [ "container-caddy-vishwambhar.service" ];
After = [ "container-caddy-vishwambhar.service" ];
RequiresMountsFor = [ "%t/containers" ];
};
Service = {
ExecStart = ''
${exec_start} \
--publish 8003:1313 \
--volume ${container_volume_path}:/src:U \
${container_image} \
server --disableFastRender --baseURL https://blog.thefossguy.com/ --appendPort=false --port=1313
'';
ExecStop = "${exec_stop}";
ExecStopPost = "${exec_stop_post}";
Environment = [ "PODMAN_SYSTEMD_UNIT=%n" ];
Type = "notify";
NotifyAccess = "all";
Restart = "always";
};
Install = {
WantedBy = [ "default.target" ];
};
};
};
};
networking.firewall.allowedTCPPorts = [
8003 # personal blog
];
imports = [
./podman-caddy-vishwambhar.nix
];
}

View File

@ -1,82 +0,0 @@
{ ... }:
{
home-manager.users.pratham = { pkgs, ... }: {
systemd.user.services =
let
container_name = "transmission-raadhe";
container_image = "lscr.io/linuxserver/transmission:latest";
container_volume_path = "/trayimurti/torrents";
exec_start = ''
${pkgs.podman}/bin/podman run \
--cgroups no-conmon \
--cidfile %t/%n.ctr-id \
--detach \
--env TZ=Asia/Kolkata \
--label io.containers.autoupdate=registry \
--name ${container_name} \
--network containers_default \
--network-alias ${container_name} \
--pull missing \
--replace \
--rm \
--sdnotify conmon'';
exec_stop = ''
${pkgs.podman}/bin/podman stop \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120
'';
exec_stop_post = ''
${pkgs.podman}/bin/podman rm \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120 \
--force
'';
in
{
"container-${container_name}" = {
Unit = {
Description = "Container service for Transmission BitTorrent client";
Documentation = [ "man:podman-run(1)" "man:podman-stop(1)" "man:podman-rm(1)" ];
Wants = [ "container-caddy-vishwambhar.service" ];
After = [ "container-caddy-vishwambhar.service" ];
RequiresMountsFor = [ "%t/containers" ];
};
Service = {
ExecStart = ''
${exec_start} \
--publish 8009:9091 \
--publish 8010:5143 \
--publish 9001:5143/udp \
--volume ${container_volume_path}/downloads:/downloads:U \
--volume ${container_volume_path}/config:/config:U \
${container_image}
'';
ExecStop = "${exec_stop}";
ExecStopPost = "${exec_stop_post}";
Environment = [ "PODMAN_SYSTEMD_UNIT=%n" ];
Type = "notify";
NotifyAccess = "all";
Restart = "always";
};
Install = {
WantedBy = [ "default.target" ];
};
};
};
};
networking.firewall.allowedTCPPorts = [
8009 # Transmission web UI
8010 # Transmission torrent comm port (TCP)
];
networking.firewall.allowedUDPPorts = [
9001 # Transmission torrent comm port (UDP)
];
imports = [
./podman-caddy-vishwambhar.nix
];
}

View File

@ -1,75 +0,0 @@
{ ... }:
{
home-manager.users.pratham = { pkgs, ... }: {
systemd.user.services =
let
container_name = "uptime-vishnu";
container_image = "docker.io/louislam/uptime-kuma:debian";
container_volume_path = "/home/pratham/container-data/volumes/uptimekuma";
exec_start = ''
${pkgs.podman}/bin/podman run \
--cgroups no-conmon \
--cidfile %t/%n.ctr-id \
--detach \
--env TZ=Asia/Kolkata \
--label io.containers.autoupdate=registry \
--name ${container_name} \
--network containers_default \
--network-alias ${container_name} \
--pull missing \
--replace \
--rm \
--sdnotify conmon'';
exec_stop = ''
${pkgs.podman}/bin/podman stop \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120
'';
exec_stop_post = ''
${pkgs.podman}/bin/podman rm \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120 \
--force
'';
in
{
"container-${container_name}" = {
Unit = {
Description = "Container service for Uptime Kuma";
Documentation = [ "man:podman-run(1)" "man:podman-stop(1)" "man:podman-rm(1)" ];
Wants = [ "container-caddy-vishwambhar.service"];
After = [ "container-caddy-vishwambhar.service"];
RequiresMountsFor = [ "%t/containers" ];
};
Service = {
ExecStart = ''
${exec_start} \
--publish 8008:3001 \
--volume ${container_volume_path}:/app/data:U \
${container_image}
'';
ExecStop = "${exec_stop}";
ExecStopPost = "${exec_stop_post}";
Environment = [ "PODMAN_SYSTEMD_UNIT=%n" ];
Type = "notify";
NotifyAccess = "all";
Restart = "always";
};
Install = {
WantedBy = [ "default.target" ];
};
};
};
};
networking.firewall.allowedTCPPorts = [
8008 # Uptime Kuma web UI
];
imports = [
./podman-caddy-vishwambhar.nix
];
}

View File

@ -1,89 +0,0 @@
{ ... }:
{
home-manager.users.pratham = { pkgs, ... }: {
systemd.user.services =
let
container_name = "";
container_image = "";
container_volume_path = "";
exec_start = ''
${pkgs.podman}/bin/podman run \
--cgroups no-conmon \
--cidfile %t/%n.ctr-id \
--detach \
--env TZ=Asia/Kolkata \
--label io.containers.autoupdate=registry \
--name ${container_name} \
--network containers_default \
--network-alias ${container_name} \
--pull missing \
--replace \
--rm \
--sdnotify conmon'';
exec_stop = ''
${pkgs.podman}/bin/podman stop \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120
'';
exec_stop_post = ''
${pkgs.podman}/bin/podman rm \
--cidfile %t/%n.ctr-id \
--ignore \
--time 120 \
--force
'';
in
{
"container-${container_name}" = {
Unit = {
Description = "Container service for ";
Documentation = [ "man:podman-run(1)" "man:podman-stop(1)" "man:podman-rm(1)" ];
Requires = [];
Wants = [];
After = [];
RequiresMountsFor = [ "%t/containers" ];
};
Service = {
ExecStart = ''
${exec_start} \
--env \
--secret \
--publish \
--volume ${container_volume_path}:/:U \
${container_image}
'';
ExecStop = "${exec_stop}";
ExecStopPost = "${exec_stop_post}";
Environment = [ "PODMAN_SYSTEMD_UNIT=%n" ];
Type = "notify";
NotifyAccess = "all";
Restart = "always";
};
Install = {
RequiredBy = [];
WantedBy = [ "default.target" ];
};
};
};
};
networking.firewall.allowedTCPPorts = [
#8001 # caddy HTTP
#8002 # caddy HTTPS
#8003 # personal blog
#8004 # machine-setup/documentation blog
#8005 # Gitea web UI
#8006 # Gitea SSH
#8007 # Nextcloud web UI
#8008 # Uptime Kuma web UI
#8009 # Transmission web UI
#8010 # Transmission torrent comm port (TCP)
];
networking.firewall.allowedUDPPorts = [
#9001 # Transmission torrent comm port (UDP)
];
imports = [];
}

View File

@ -0,0 +1,46 @@
{ config
, lib
, pkgs
, systemUser
, ...
}:
{
virtualisation = {
oci-containers.backend = "podman";
libvirtd = {
enable = true;
allowedBridges = [ "virbr0" ];
onShutdown = "shutdown";
qemu = {
ovmf.enable = true;
ovmf.packages = [ pkgs.OVMF ];
package = pkgs.qemu_kvm;
runAsRoot = false; # not sure about this
swtpm.enable = true;
verbatimConfig = ''
user = "${systemUser.username}"
group = "${systemUser.username}"
'';
};
};
podman = {
enable = true;
defaultNetwork.settings = { dns_enabled = true; };
dockerCompat = true;
dockerSocket.enable = true;
extraPackages = [ pkgs.buildah ];
networkSocket.openFirewall = true;
autoPrune = {
enable = true;
dates = "weekly";
flags = [ "--all" ];
};
};
};
}

View File

@ -1,27 +0,0 @@
#!/usr/bin/env nix-shell
#!nix-shell -i bash --packages git
set -xeuf -o pipefail
if [ "${USER}" = 'pratham' ] && [ -n "${HOME}" ]; then
# get dotfiles
git clone --bare https://gitlab.com/thefossguy/dotfiles.git "${HOME}/.dotfiles"
git --git-dir="${HOME}/.dotfiles" --work-tree="${HOME}" checkout -f
# generate SSH keys
chmod 700 "${HOME}/.ssh"
pushd "${HOME}/.ssh"
clear -x
ssh-keygen -t ed25519 -f git
ssh-keygen -t ed25519 -f ssh
popd
# get nixos config
mkdir -vp "${HOME}/my-git-repos/pratham"
pushd "${HOME}/my-git-repos/pratham"
git clone https://gitlab.com/thefossguy/prathams-nixos
popd
else
>&2 echo "$0: You are not me"
exit 1
fi

18
scripts/chroot-user-setup.sh Executable file
View File

@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -xeuf -o pipefail
if [[ -n "${HOME}" ]]; then
# get dotfiles
git clone --bare https://gitlab.com/thefossguy/dotfiles.git "${HOME}/.dotfiles"
git --git-dir="${HOME}/.dotfiles" --work-tree="${HOME}" checkout -f
# "generate" SSH keys
chmod 700 "${HOME}/.ssh"
touch "${HOME}/.ssh"/{ssh,git}{,.pub}
else
# shellcheck disable=SC2016
echo 'ERROR: For some reason $HOME is not defined...'
exit 1
fi

View File

@ -1,93 +0,0 @@
#!/usr/bin/env nix-shell
#!nix-shell -i bash --packages
# not using 'set -u' because 'CPU_VENDOR' **will** be empty on non-x86_64 systems
set -xef -o pipefail
# always make sure that the file exists because it is included in the master config
touch "${CUSTOM_HOST_CONFIG}"
IMPORT_MODULES=('./includes/zfs-configuration.nix')
# setup hostname and hostid
cat << EOF > "${CUSTOM_HOST_CONFIG}"
{ config, pkgs, lib, ... }:
{
networking = {
hostId = "${NETWORKING_HOSTID}";
hostName = "${MACHINE_HOSTNAME}";
};
EOF
if [ "${CPU_VENDOR}" = 'AMD' ]; then
cat << EOF > "${CUSTOM_HOST_CONFIG}"
hardware.cpu.amd.updateMicrocode = true;
boot.kernelModules = [ "kvm-amd" ];
boot.extraModprobeConfig = "options kvm_amd nested=1";
EOF
elif [ "${CPU_VENDOR}" = 'Intel' ]; then
cat << EOF > "${CUSTOM_HOST_CONFIG}"
hardware.cpu.intel.updateMicrocode = true;
boot.kernelModules = [ "kvm-intel" ];
boot.extraModprobeConfig = "options kvm_intel nested=1";
EOF
fi
if [ "${PARTITION_LAYOUT}" = 'desktop' ]; then
IMPORT_MODULES+=('./desktop-env/kde-plasma-wayland-configuration.nix')
# add GPU drivers only if user selects a DE/WM
if [ "${OSS_GPU_DRIVERS}" = 'true' ]; then
if [ "${GPU_AMD}" = 'true' ]; then
IMPORT_MODULES+=('./gpu/amd-gpu.nix')
fi
if [ "${GPU_INTEL}" = 'true' ]; then
IMPORT_MODULES+=('./gpu/intel-gpu.nix')
fi
elif [ "${OSS_GPU_DRIVERS}" = 'false' ]; then
# if an NVIDIA GPU is detected, install only NVIDIA drivers such that
# another GPU vendor's drivers aren't loaded and cause headache
IMPORT_MODULES+=('./gpu/nvidia-gpu.nix')
fi
fi
if [ "${MACHINE_HOSTNAME}" = 'reddish' ]; then
IMPORT_MODULES+=('./user-services/podman/podman-master.nix')
fi
if [ "${BATTERY_POWERED_DEVICE}" = 'true' ]; then
IMPORT_MODULES+=('./includes/battery-and-power-management.nix')
fi
cat << EOF >> "${CUSTOM_HOST_CONFIG}"
#boot.kernelPackages = pkgs.linuxPackages_latest;
boot.loader.efi.canTouchEfiVariables = ${CAN_TOUCH_EFI_VARS};
#boot.tmp.useTmpfs = true; # mount the tmpfs on /tmp during boot
#boot.tmp.tmpfsSize = "10%";
zramSwap = {
enable = true;
algorithm = "zstd";
memoryPercent = 50;
};
EOF
cat << EOF >> "${CUSTOM_HOST_CONFIG}"
imports = [
EOF
for MODULE in "${IMPORT_MODULES[@]}"; do
cat << EOF >> "${CUSTOM_HOST_CONFIG}"
${MODULE}
EOF
done
cat << EOF >> "${CUSTOM_HOST_CONFIG}"
];
}
EOF

49
scripts/get-mount-path-uuid.sh Executable file
View File

@ -0,0 +1,49 @@
#!/usr/bin/env bash
set -euf -o pipefail
if [[ -z "${MOUNT_PATH:-}" ]]; then
# shellcheck disable=SC2016
echo 'ERROR: $MOUNT_PATH is undefined'
exit 1
fi
if [[ -z "${HOSTNAME:-}" ]]; then
# shellcheck disable=SC2016
echo 'ERROR: $HOSTNAME is undefined'
exit 1
fi
BOOT_MOUNT_PATH='fileSystems."/boot"'
ROOT_MOUNT_PATH='fileSystems."/"'
HOME_MOUNT_PATH='fileSystems."/home"'
VARL_MOUNT_PATH='fileSystems."/var"'
# i know `case-esac` but that's ugly
if [[ "${MOUNT_PATH}" == 'boot' ]]; then
MOUNT_PATH="${BOOT_MOUNT_PATH}"
elif [[ "${MOUNT_PATH}" == 'root' ]]; then
MOUNT_PATH="${ROOT_MOUNT_PATH}"
elif [[ "${MOUNT_PATH}" == 'home' ]]; then
MOUNT_PATH="${HOME_MOUNT_PATH}"
elif [[ "${MOUNT_PATH}" == 'var' ]]; then
MOUNT_PATH="${VARL_MOUNT_PATH}"
else
# shellcheck disable=SC2016
echo 'ERROR: invalid $MOUNT_PATH; values are: boot, root, home, var'
exit 1
fi
TARGET_FILE="nixos-configuration/hosts/${HOSTNAME}/default.nix"
if [[ -f "${TARGET_FILE}" ]]; then
grep -A 1 "${MOUNT_PATH}" "${TARGET_FILE}" | tail -n 1 | \
grep 'device = "/dev/disk/by-uuid/' | \
rev | cut -c 3- | rev | \
sed -e 's@/@ @g' | \
awk '{print $NF}'
else
# shellcheck disable=SC2016
echo 'ERROR: No file found for $HOSTNAME'
exit 1
fi

View File

@ -1,44 +0,0 @@
#!/usr/bin/env nix-shell
#!nix-shell -i bash --packages gnutar perl unzip wget
# not using 'set -f' because file globbing is necessary
set -xeu -o pipefail
TMP_FIRMWARE_DIR="$(pwd)/rpi-firmware"
TMP_OUT_DIR="$(pwd)/out"
RPI4_EFI_FIRMWARE_TAG='v1.35'
RPI_VNDR_FIRMWARE_TAG='1.20230405'
RPI4_EFI_FIRMWARE_FILE="${TMP_FIRMWARE_DIR}/RPi4_UEFI_Firmware_${RPI4_EFI_FIRMWARE_TAG}.zip"
RPI_VNDR_FIRMWARE_FILE="${TMP_FIRMWARE_DIR}/${RPI_VNDR_FIRMWARE_TAG}.tar.gz"
RPI4_EFI_FIRMWARE_DIR="${TMP_FIRMWARE_DIR}/rpi-${RPI4_EFI_FIRMWARE_TAG}"
RPI_VNDR_FIRMWARE_DIR="${TMP_FIRMWARE_DIR}/firmware-${RPI_VNDR_FIRMWARE_TAG}"
RPI4_EFI_FIRMWARE_HASH='4c6f73a0af93d545bf09e40c99c581d01403bb09af84d5434cb970c7be66a1251c1ceebd317b1aa411a8b733f19abc957086c3b169b8c1dc72b6ff4bd601658d'
RPI_VNDR_FIRMWARE_HASH='ddc9baeba4e2e442bfe41e427c7ecdd38ee6d44ac4e7c297ae7d5a6c64b0aa1a81206929baeb9aceb74de6f96707b30040e82450ef4f01a78b958299c72e3857'
[ -d "${TMP_FIRMWARE_DIR}" ] || mkdir "${TMP_FIRMWARE_DIR}"
[ -d "${TMP_OUT_DIR}" ] && rm -rf "${TMP_OUT_DIR}"
mkdir "${TMP_OUT_DIR}"
while ! sha512sum "${RPI4_EFI_FIRMWARE_FILE}" | grep "${RPI4_EFI_FIRMWARE_HASH}"; do
rm -f "${RPI4_EFI_FIRMWARE_FILE}"
wget --secure-protocol=TLSv1_3 "https://github.com/pftf/RPi4/releases/download/${RPI4_EFI_FIRMWARE_TAG}/RPi4_UEFI_Firmware_${RPI4_EFI_FIRMWARE_TAG}.zip" --output-document "${RPI4_EFI_FIRMWARE_FILE}"
done
while ! sha512sum "${RPI_VNDR_FIRMWARE_FILE}" | grep "${RPI_VNDR_FIRMWARE_HASH}"; do
rm -f "${RPI_VNDR_FIRMWARE_FILE}"
wget --secure-protocol=TLSv1_3 "https://github.com/raspberrypi/firmware/archive/refs/tags/${RPI_VNDR_FIRMWARE_TAG}.tar.gz" --output-document "${RPI_VNDR_FIRMWARE_FILE}"
done
rm -rf "${RPI4_EFI_FIRMWARE_DIR}"
rm -rf "${RPI_VNDR_FIRMWARE_DIR}"
unzip "${RPI4_EFI_FIRMWARE_FILE}" -d "${RPI4_EFI_FIRMWARE_DIR}"
tar -xvf "${RPI_VNDR_FIRMWARE_FILE}" -C "${TMP_FIRMWARE_DIR}"
cp -rf "${RPI4_EFI_FIRMWARE_DIR}"/* "${TMP_OUT_DIR}/"
cp -rf "${RPI_VNDR_FIRMWARE_DIR}"/boot/* "${TMP_OUT_DIR}/"
rm -vf "${TMP_OUT_DIR}"/*kernel*
rm -vf "${TMP_OUT_DIR}"/Readme.md
cp -r "$(pwd)"/out/* "${RPI_FIRMWARE_PATH}"

22
scripts/mk-iso.sh Executable file
View File

@ -0,0 +1,22 @@
#!/usr/bin/env bash
set -eu -o pipefail
if [ "$(uname -s)" != 'Linux' ]; then
echo 'What operating system even is this?'
exit 1
fi
set -x
time nom build --show-trace ".#isos.$(uname -m)"
for resultISO in $(basename result/iso/nixos-*-linux.iso); do
if [ ! -f "${resultISO}" ]; then
cp result/iso/"${resultISO}" .
fi
if [ ! -f "${resultISO}.sha512" ]; then
sha512sum "${resultISO}" | awk '{print $1}' 1> "${resultISO}.sha512"
fi
chown "${USER}:${USER}" "${resultISO}"
chmod 644 "${resultISO}"
done

52
scripts/partition-disk.sh Executable file
View File

@ -0,0 +1,52 @@
#!/usr/bin/env bash
set -xeuf -o pipefail
# do this first to fail early if this `exit 1`s
BOOT_UUID="$(MOUNT_PATH=boot scripts/get-mount-path-uuid.sh)"
ROOT_UUID="$(MOUNT_PATH=root scripts/get-mount-path-uuid.sh)"
HOME_UUID="$(MOUNT_PATH=home scripts/get-mount-path-uuid.sh)"
VARL_UUID="$(MOUNT_PATH=var scripts/get-mount-path-uuid.sh)"
cat << EOF | fdisk --wipe always "${TARGET_DRIVE}"
g
n
1
+1G
n
2
+${ROOT_PART_SIZE}G
n
3
-6G
n
4
w
EOF
sync; sync; sync; sync;
hdparm -z "${TARGET_DRIVE}"
BOOT_PART="${INTERMEDIATE_PART}1"
ROOT_PART="${INTERMEDIATE_PART}2"
HOME_PART="${INTERMEDIATE_PART}3"
VARL_PART="${INTERMEDIATE_PART}4"
mkfs.fat -F 32 -n nixboot "${BOOT_PART}" -i "${BOOT_UUID//-/}"
mkfs.xfs -f -L nixroot "${ROOT_PART}" -m uuid="${ROOT_UUID}"
mkfs.xfs -f -L nixhome "${HOME_PART}" -m uuid="${HOME_UUID}"
mkfs.xfs -f -L nixvarp "${VARL_PART}" -m uuid="${VARL_UUID}"
parted -s "${TARGET_DRIVE}" -- set 1 esp on
BY_UUID_PATH='/dev/disk/by-uuid'
BOOT_PART="${BY_UUID_PATH}/${BOOT_UUID}"
ROOT_PART="${BY_UUID_PATH}/${ROOT_UUID}"
HOME_PART="${BY_UUID_PATH}/${HOME_UUID}"
VARL_PART="${BY_UUID_PATH}/${VARL_UUID}"
mount -o async,lazytime,relatime "${ROOT_PART}" "${MOUNT_PATH}"
mount -o async,lazytime,relatime --mkdir "${BOOT_PART}" "${MOUNT_PATH}/boot"
mount -o async,lazytime,relatime --mkdir "${HOME_PART}" "${MOUNT_PATH}/home"
mount -o async,lazytime,relatime --mkdir "${VARL_PART}" "${MOUNT_PATH}/var"

View File

@ -1,64 +0,0 @@
#!/usr/bin/env nix-shell
#!nix-shell -i bash --packages
set -xeuf -o pipefail
export RPI_FIRMWARE_PATH="${MOUNT_PATH}/raspberry-pi/firmware"
RASP_PART="${INTERMEDIATE_PART}1"
BOOT_PART="${INTERMEDIATE_PART}2"
ROOT_PART="${INTERMEDIATE_PART}3"
HOME_PART="${INTERMEDIATE_PART}4"
VARL_PART="${INTERMEDIATE_PART}5"
cat << EOF | fdisk --wipe always "${OS_DRIVE}"
g
n
1
+${RASP_PART_SIZE}
n
2
+${BOOT_PART_SIZE}
n
3
+${ROOT_PART_SIZE}
n
4
-${VARL_PART_SIZE}
n
5
t
1
0b
t
2
0b
w
EOF
sync; sync; sync; sync;
sleep 10
sync; sync; sync; sync;
mkfs.fat -F 32 -n pftf "${RASP_PART}" -i "${RPIF_UUID}"
mkfs.fat -F 32 -n nixboot "${BOOT_PART}" -i "${BOOT_UUID}"
parted -s "${OS_DRIVE}" -- set 1 esp on
parted -s "${OS_DRIVE}" -- set 2 esp on
mkfs.xfs -f -L nixroot "${ROOT_PART}"
mkfs.xfs -f -L nixhome "${HOME_PART}"
mkfs.xfs -f -L nixvarp "${VARL_PART}"
mount -o async,lazytime,relatime "${ROOT_PART}" "${MOUNT_PATH}"
mount -o async,lazytime --mkdir "${BOOT_PART}" "${MOUNT_PATH}/boot"
mount -o async,lazytime --mkdir "${HOME_PART}" "${MOUNT_PATH}/home"
mount -o async,lazytime --mkdir "${VARL_PART}" "${MOUNT_PATH}/var"
mount -o async,lazytime --mkdir "${RASP_PART}" "${MOUNT_PATH}/raspberry-pi/firmware"
"$(pwd)/scripts/get-raspi-4-firmware.sh"
umount "${MOUNT_PATH}/raspberry-pi/firmware"
fdisk -l "${OS_DRIVE}"

View File

@ -1,46 +0,0 @@
#!/usr/bin/env nix-shell
#!nix-shell -i bash --packages
set -xeuf -o pipefail
BOOT_PART="${INTERMEDIATE_PART}1"
ROOT_PART="${INTERMEDIATE_PART}2"
HOME_PART="${INTERMEDIATE_PART}3"
VARL_PART="${INTERMEDIATE_PART}4"
cat << EOF | fdisk --wipe always "${OS_DRIVE}"
g
n
1
+${BOOT_PART_SIZE}
n
2
+${ROOT_PART_SIZE}
n
3
-${VARL_PART_SIZE}
n
4
w
EOF
sync; sync; sync; sync;
sleep 10
sync; sync; sync; sync;
mkfs.fat -F 32 -n nixboot "${BOOT_PART}" -i "${BOOT_UUID}"
parted -s "${OS_DRIVE}" -- set 1 esp on
mkfs.xfs -f -L nixroot "${ROOT_PART}"
mkfs.xfs -f -L nixhome "${HOME_PART}"
mkfs.xfs -f -L nixvarp "${VARL_PART}"
mount -o async,lazytime,relatime "${ROOT_PART}" "${MOUNT_PATH}"
mount -o async,lazytime --mkdir "${BOOT_PART}" "${MOUNT_PATH}/boot"
mount -o async,lazytime --mkdir "${HOME_PART}" "${MOUNT_PATH}/home"
mount -o async,lazytime --mkdir "${VARL_PART}" "${MOUNT_PATH}/var"
fdisk -l "${OS_DRIVE}"