#!/usr/bin/env nu

def main [_config: string]: nothing -> nothing {
  const WRAPPED_DRACUT_PATH = '/usr/libexec/rpm-ostree/wrapped/dracut'
  const DRACUT_PATH = '/usr/bin/dracut'
  const KERNEL_MODULES_PATH = '/usr/lib/modules'

  let rpm_ostree_exists = (^command -v rpm-ostree | complete).exit_code == 0
  let bootc_exists = (^command -v bootc | complete).exit_code == 0

  if not ($rpm_ostree_exists or $bootc_exists) {
    return (error make {
      msg: 'This module is only compatible with Fedora Atomic images'
      labels: [
        {
          text: 'Checks for rpm-ostree'
          span: (metadata $rpm_ostree_exists).span
        }
        {
          text: 'Checks for bootc'
          span: (metadata $bootc_exists).span
        }
      ]
    })
  }

  let dracut_path = if ($WRAPPED_DRACUT_PATH | path exists) {
    $WRAPPED_DRACUT_PATH
  } else {
    $DRACUT_PATH
  }

  ls $KERNEL_MODULES_PATH
    | get name
    | path basename
    | each {|kernel|
      print $'(ansi green)Generating initramfs for kernel (ansi cyan)($kernel)(ansi reset)'
      let image_path = [$KERNEL_MODULES_PATH $kernel initramfs.img] | path join
      try {
        (^$dracut_path
          --no-hostonly
          --kver $kernel
          --reproducible
          -v
          --add ostree
          -f $image_path)
      }
      chmod 0600 $image_path
      print $"(ansi green)Finished generating initramfs for kernel (ansi cyan)($kernel)(ansi reset)\n"
    }

  print $'(ansi green)Generating initramfs images complete(ansi reset)'
}
