rbtohex() {
    ( od -An -vtx1 | tr -d ' \n' )
}

hextorb() {
    ( tr '[:lower:]' '[:upper:]' | sed -e 's/\([0-9A-F]\{2\}\)/\\\\\\x\1/gI'| xargs printf )
}

# Setup
# nix-env -i gcc-wrapper
# nix-env -i yubikey-personalization
# nix-env -i openssl
# Use nix-shell https://github.com/sgillespie/nixos-yubikey-luks/archive/master.tar.gz

# Compile correct version of OpenSSL key derivation
cc -O3 -I$(nix-build "<nixpkgs>" --no-build-output -A openssl.dev)/include -L$(nix-build "<nixpkgs>" --no-build-output -A openssl.out)/lib $(nix eval "(with import <nixpkgs> {}; pkgs.path)")/nixos/modules/system/boot/pbkdf2-sha512.c -o ./pbkdf2-sha512 -lcrypto

# Yubikey Setup
SLOT=2
ykpersonalize -"$SLOT" -ochal-resp -ochal-hmac
SALT_LENGTH=16
salt="$(dd if=/dev/random bs=1 count=$SALT_LENGTH 2>/dev/null | rbtohex)"
k_user=PASSWORDCHANGEMEPLAEASES 
challenge="$(echo -n $salt | openssl dgst -binary -sha512 | rbtohex)"
response="$(ykchalresp -2 -x $challenge 2>/dev/null)"

# Setup LUKS device
KEY_LENGTH=512
ITERATIONS=1000000
k_luks="$(echo -n $k_user | ./pbkdf2-sha512 $(($KEY_LENGTH / 8)) $ITERATIONS $response | rbtohex)"

EFI_PART=/dev/sda1
LUKS_PART=/dev/sda2
EFI_MNT=/boot/
mkdir -p "$EFI_MNT"
mkfs.fat -F 32 -n boot "$EFI_PART"
mount "$EFI_PART" "$EFI_MNT"
STORAGE=/crypt-storage/default
mkdir -p "$(dirname $EFI_MNT$STORAGE)"
echo -ne "$salt\n$ITERATIONS" > $EFI_MNT$STORAGE
CIPHER=aes-xts-plain64
HASH=sha512
echo -n "$k_luks" | hextorb | cryptsetup luksFormat --cipher="$CIPHER" --key-size="$KEY_LENGTH" --hash="$HASH" --key-file=- "$LUKS_PART"
umount "$EFI_MNT"

# LVM Setup
LUKSROOT=crypthome
echo -n "$k_luks" | hextorb | cryptsetup luksOpen $LUKS_PART $LUKSROOT --key-file=- 
pvcreate "/dev/mapper/$LUKSROOT"
VGNAME=partitions
vgcreate "$VGNAME" "/dev/mapper/$LUKSROOT"
lvcreate -L 2G -n swap "$VGNAME"
FSROOT=fsroot
lvcreate -l 100%FREE -n "$FSROOT" "$VGNAME"

vgchange -ay
mkswap -L swap /dev/partitions/swap

# BTRFS Setup
mkfs.btrfs -L "$FSROOT" "/dev/partitions/$FSROOT"

# incase the above breaks
#mkdir /mnt-root
#touch /mnt-root/nix-store.squashfs

mount "/dev/partitions/$FSROOT" /mnt
cd /mnt
btrfs subvolume create root
btrfs subvolume create home
cd
umount /mnt
mount -o subvol=root "/dev/partitions/$FSROOT" /mnt
mkdir /mnt/home
mount -o subvol=home "/dev/partitions/$FSROOT" /mnt/home
mkdir /mnt/boot
mount "$EFI_PART" /mnt/boot

swapon /dev/partitions/swap

# Install NixOS
nixos-generate-config --root /mnt

# Change the config
cat > /mnt/etc/nixos/configuration.nix <<'endmsg'
{ config, pkgs, ... }:

{
  imports =
    [ # Include the results of the hardware scan.
      ./hardware-configuration.nix
    ];

  boot.loader.grub.enable = true;
  boot.loader.grub.version = 2;
  # Define on which hard drive you want to install Grub.
  boot.loader.grub.device = "/dev/sda"; # or "nodev" for efi only

  # Minimal list of modules to use the EFI system partition and the YubiKey
  boot.initrd.kernelModules = [ "vfat" "nls_cp437" "nls_iso8859-1" "usbhid" ];
  
  # Enable support for the YubiKey PBA
  boot.initrd.luks.yubikeySupport = true;
  
  # Configuration to use your Luks device
  boot.initrd.luks.devices = {
    "crypthome" = {
      device = "/dev/sda2";
      preLVM = true; # You may want to set this to false if you need to start a network service first
      yubikey = {
        slot = 2;
        twoFactor = true; # Set to false if you did not set up a user password.
        storage = {
          device = "/dev/sda1";
        };
      };
    }; 
  };

  # Enable Flakes
  nix = {
    package = pkgs.nixUnstable;
    extraOptions = ''
      experimental-features = nix-command flakes
    '';
   };

  networking.hostName = "curve"; # Define your hostname.
  networking.wireless.enable = true;  # Enables wireless support via wpa_supplicant.

  time.timeZone = "Australia/Brisbane";

  networking.useDHCP = false;
  networking.interfaces.enp0s31f6.useDHCP = true;
  networking.interfaces.wlp3s0.useDHCP = true;

  # Select internationalisation properties.
  i18n.defaultLocale = "en_US.UTF-8";
  # console = {
  #   font = "Lat2-Terminus16";
  #   keyMap = "us";
  # };

  services.xserver.layout = "us,dvorak";

  sound.enable = true;
  hardware.pulseaudio.enable = true;

  services.xserver.libinput.enable = true;

  # Hmmm maybe somewhere else? 
  users.users.anish = {
    isNormalUser = true;
    extraGroups = [ "wheel" ]; 
  };

  # Enable the OpenSSH daemon.
  # services.openssh.enable = true;

  # This value determines the NixOS release from which the default
  # settings for stateful data, like file locations and database versions
  # on your system were taken. It‘s perfectly fine and recommended to leave
  # this value at the release version of the first install of this system.
  # Before changing this value read the documentation for this option
  # (e.g. man configuration.nix or on https://nixos.org/nixos/options.html).
  system.stateVersion = "21.05"; # Did you read the comment?
}

endmsg

cd /mnt
nixos-install --root /mnt
passwd
