code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019 Ludovic Courtès <ludo@gnu.org>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (gnu system accounts)
  #:use-module (guix records)
  #:use-module (ice-9 match)
  #:export (user-account
            user-account?
            user-account-name
            user-account-password
            user-account-uid
            user-account-group
            user-account-supplementary-groups
            user-account-comment
            user-account-home-directory
            user-account-create-home-directory?
            user-account-shell
            user-account-system?

            user-group
            user-group?
            user-group-name
            user-group-password
            user-group-id
            user-group-system?

            sexp->user-account
            sexp->user-group

            default-shell))

;;; Commentary:
;;;
;;; Data structures representing user accounts and user groups.  This is meant
;;; to be used both on the host side and at run time--e.g., in activation
;;; snippets.
;;;
;;; Code:

(define default-shell
  ;; Default shell for user accounts (a string or string-valued gexp).
  (make-parameter "/bin/sh"))

(define-record-type* <user-account>
  user-account make-user-account
  user-account?
  (name           user-account-name)
  (password       user-account-password (default #f))
  (uid            user-account-uid (default #f))
  (group          user-account-group)             ; number | string
  (supplementary-groups user-account-supplementary-groups
                        (default '()))            ; list of strings
  (comment        user-account-comment (default ""))
  (home-directory user-account-home-directory (thunked)
                  (default (default-home-directory this-record)))
  (create-home-directory? user-account-create-home-directory? ;Boolean
                          (default #t))
  (shell          user-account-shell              ; gexp
                  (default (default-shell)))
  (system?        user-account-system?            ; Boolean
                  (default #f)))

(define-record-type* <user-group>
  user-group make-user-group
  user-group?
  (name           user-group-name)
  (password       user-group-password (default #f))
  (id             user-group-id (default #f))
  (system?        user-group-system?              ; Boolean
                  (default #f)))

(define (default-home-directory account)
  "Return the default home directory for ACCOUNT."
  (string-append "/home/" (user-account-name account)))

(define (sexp->user-group sexp)
  "Take SEXP, a tuple as returned by 'user-group->gexp', and turn it into a
user-group record."
  (match sexp
    ((name password id system?)
     (user-group (name name)
                 (password password)
                 (id id)
                 (system? system?)))))

(define (sexp->user-account sexp)
  "Take SEXP, a tuple as returned by 'user-account->gexp', and turn it into a
user-account record."
  (match sexp
    ((name uid group supplementary-groups comment home-directory
           create-home-directory? shell password system?)
     (user-account (name name) (uid uid) (group group)
                   (supplementary-groups supplementary-groups)
                   (comment comment)
                   (home-directory home-directory)
                   (create-home-directory? create-home-directory?)
                   (shell shell) (password password)
                   (system? system?)))))


code:
;; This is an operating system configuration template
;; for a "bare bones" setup for an ASUS C201PA.

(use-modules (gnu) (gnu bootloader depthcharge))
(use-service-modules networking ssh)
(use-package-modules linux screen)

(operating-system
  (host-name "komputilo")
  (timezone "Europe/Berlin")
  (locale "en_US.utf8")

  ;; Assuming /dev/mmcblk0p1 is the kernel partition, and
  ;; "my-root" is the label of the target root file system.
  (bootloader (bootloader-configuration
                (bootloader depthcharge-bootloader)
                (target "/dev/mmcblk0p1")))

  ;; The ASUS C201PA requires a very particular kernel to boot,
  ;; as well as the following arguments.
  (kernel linux-libre-arm-generic)
  (kernel-arguments '("console=tty1"))

  ;; We do not need any special modules for initrd, and the
  ;; PrawnOS kernel does not include many of the normal ones.
  (initrd-modules '())

  (file-systems (cons (file-system
                        (device (file-system-label "my-root"))
                        (mount-point "/")
                        (type "ext4"))
                      %base-file-systems))

  ;; This is where user accounts are specified.  The "root"
  ;; account is implicit, and is initially created with the
  ;; empty password.
  (users (cons (user-account
                (name "alice")
                (comment "Bob's sister")
                (group "users")

                ;; Adding the account to the "wheel" group
                ;; makes it a sudoer.  Adding it to "audio"
                ;; and "video" allows the user to play sound
                ;; and access the webcam.
                (supplementary-groups '("wheel"
                                        "audio" "video"))
                (home-directory "/home/alice"))
               %base-user-accounts))

  ;; Globally-installed packages.
  (packages (cons screen %base-packages))

  ;; Add services to the baseline: a DHCP client and
  ;; an SSH server.
  (services (append (list (service dhcp-client-service-type)
                          (service openssh-service-type
                                   (openssh-configuration
                                    (port-number 2222))))
                    %base-services)))

license: mit


code:
;; This is an operating system configuration template
;; for a "bare bones" setup, with no X11 display server.

(use-modules (gnu))
(use-service-modules networking ssh)
(use-package-modules screen ssh)

(operating-system
  (host-name "komputilo")
  (timezone "Europe/Berlin")
  (locale "en_US.utf8")

  ;; Boot in "legacy" BIOS mode, assuming /dev/sdX is the
  ;; target hard disk, and "my-root" is the label of the target
  ;; root file system.
  (bootloader (bootloader-configuration
                (bootloader grub-bootloader)
                (target "/dev/sdX")))
  (file-systems (cons (file-system
                        (device (file-system-label "my-root"))
                        (mount-point "/")
                        (type "ext4"))
                      %base-file-systems))

  ;; This is where user accounts are specified.  The "root"
  ;; account is implicit, and is initially created with the
  ;; empty password.
  (users (cons (user-account
                (name "alice")
                (comment "Bob's sister")
                (group "users")

                ;; Adding the account to the "wheel" group
                ;; makes it a sudoer.  Adding it to "audio"
                ;; and "video" allows the user to play sound
                ;; and access the webcam.
                (supplementary-groups '("wheel"
                                        "audio" "video")))
               %base-user-accounts))

  ;; Globally-installed packages.
  (packages (cons screen %base-packages))

  ;; Add services to the baseline: a DHCP client and
  ;; an SSH server.
  (services (append (list (service dhcp-client-service-type)
                          (service openssh-service-type
                                   (openssh-configuration
                                    (openssh openssh-sans-x)
                                    (port-number 2222))))
                    %base-services)))


code:
;; -*-scheme-*-

;; This is an operating system configuration template
;; for a "bare bones" setup, with no X11 display server.

;; To build a disk image for a virtual machine, do
;;
;;     ./pre-inst-env guix system disk-image --target=i586-pc-gnu \
;;         gnu/system/examples/bare-hurd.tmpl
;;
;; You may run it like so
;;
;;     guix environment --ad-hoc qemu -- qemu-system-i386 -enable-kvm -m 512M \
;;      -device rtl8139,netdev=net0 -netdev user,id=net0,hostfwd=tcp:127.0.0.1:10022-:2222 \
;;      -snapshot -hda <the-image>
;;
;; and use it like
;;
;;     ssh -p 10022 root@localhost
;;     guix build -e '(@@ (gnu packages commencement) gnu-make-boot0)'
;;
;; or even (if you use --image-size=3G)
;;
;;     guix build hello

(use-modules (gnu) (gnu system hurd) (guix utils))
(use-service-modules ssh)
(use-package-modules ssh)

(define %hurd-os
  (operating-system
    (inherit %hurd-default-operating-system)
    (bootloader (bootloader-configuration
                 (bootloader grub-minimal-bootloader)
                 (target "/dev/sdX")))
    (file-systems (cons (file-system
                          (device (file-system-label "my-root"))
                          (mount-point "/")
                          (type "ext2"))
                        %base-file-systems))
    (host-name "guixygnu")
    (timezone "Europe/Amsterdam")
    (packages (cons openssh-sans-x %base-packages/hurd))
    (services (cons (service openssh-service-type
                             (openssh-configuration
                              (openssh openssh-sans-x)
                              (use-pam? #f)
                              (port-number 2222)
                              (permit-root-login #t)
                              (allow-empty-passwords? #t)
                              (password-authentication? #t)))
               %base-services/hurd))))

%hurd-os


code:
;; This is an operating system configuration template
;; for a "bare bones" setup on BeagleBone Black board.

(use-modules (gnu) (gnu bootloader u-boot))
(use-service-modules networking)
(use-package-modules bootloaders screen ssh)

(operating-system
  (host-name "komputilo")
  (timezone "Europe/Berlin")
  (locale "en_US.utf8")

  ;; Assuming /dev/mmcblk1 is the eMMC, and "my-root" is
  ;; the label of the target root file system.
  (bootloader (bootloader-configuration
               (bootloader u-boot-beaglebone-black-bootloader)
               (target "/dev/mmcblk1")))

  ;; This module is required to mount the SD card.
  (initrd-modules (cons "omap_hsmmc" %base-initrd-modules))

  (file-systems (cons (file-system
                        (device (file-system-label "my-root"))
                        (mount-point "/")
                        (type "ext4"))
                      %base-file-systems))

  ;; This is where user accounts are specified.  The "root"
  ;; account is implicit, and is initially created with the
  ;; empty password.
  (users (cons (user-account
                (name "alice")
                (comment "Bob's sister")
                (group "users")

                ;; Adding the account to the "wheel" group
                ;; makes it a sudoer.  Adding it to "audio"
                ;; and "video" allows the user to play sound
                ;; and access the webcam.
                (supplementary-groups '("wheel"
                                        "audio" "video")))
               %base-user-accounts))

  ;; Globally-installed packages.
  (packages (append (list screen openssh) %base-packages))

  (services (append (list (service dhcp-client-service-type)
                          ;; mingetty does not work on serial lines.
                          ;; Use agetty with board-specific serial parameters.
                          (agetty-service
                           (agetty-configuration
                            (extra-options '("-L"))
                            (baud-rate "115200")
                            (term "vt100")
                            (tty "ttyO0"))))
                  %base-services)))


code:
;; This is an operating system configuration template
;; for a "desktop" setup with GNOME and Xfce where the
;; root partition is encrypted with LUKS.

(use-modules (gnu) (gnu system nss))
(use-service-modules desktop xorg)
(use-package-modules certs gnome)

(operating-system
  (host-name "antelope")
  (timezone "Europe/Paris")
  (locale "en_US.utf8")

  ;; Choose US English keyboard layout.  The "altgr-intl"
  ;; variant provides dead keys for accented characters.
  (keyboard-layout (keyboard-layout "us" "altgr-intl"))

  ;; Use the UEFI variant of GRUB with the EFI System
  ;; Partition mounted on /boot/efi.
  (bootloader (bootloader-configuration
                (bootloader grub-efi-bootloader)
                (target "/boot/efi")
                (keyboard-layout keyboard-layout)))

  ;; Specify a mapped device for the encrypted root partition.
  ;; The UUID is that returned by 'cryptsetup luksUUID'.
  (mapped-devices
   (list (mapped-device
          (source (uuid "12345678-1234-1234-1234-123456789abc"))
          (target "my-root")
          (type luks-device-mapping))))

  (file-systems (append
                 (list (file-system
                         (device (file-system-label "my-root"))
                         (mount-point "/")
                         (type "ext4")
                         (dependencies mapped-devices))
                       (file-system
                         (device (uuid "1234-ABCD" 'fat))
                         (mount-point "/boot/efi")
                         (type "vfat")))
                 %base-file-systems))

  ;; Create user `bob' with `alice' as its initial password.
  (users (cons (user-account
                (name "bob")
                (comment "Alice's brother")
                (password (crypt "alice" "$6$abc"))
                (group "users")
                (supplementary-groups '("wheel" "netdev"
                                        "audio" "video")))
               %base-user-accounts))

  ;; This is where we specify system-wide packages.
  (packages (append (list
                     ;; for HTTPS access
                     nss-certs
                     ;; for user mounts
                     gvfs)
                    %base-packages))

  ;; Add GNOME and Xfce---we can choose at the log-in screen
  ;; by clicking the gear.  Use the "desktop" services, which
  ;; include the X11 log-in service, networking with
  ;; NetworkManager, and more.
  (services (append (list (service gnome-desktop-service-type)
                          (service xfce-desktop-service-type)
                          (set-xorg-configuration
                           (xorg-configuration
                            (keyboard-layout keyboard-layout))))
                    %desktop-services))

  ;; Allow resolution of '.local' host names with mDNS.
  (name-service-switch %mdns-host-lookup-nss))


code:
;; This is an operating system configuration template for a "Docker image"
;; setup, so it has barely any services at all.

(use-modules (gnu))

(operating-system
  (host-name "komputilo")
  (timezone "Europe/Berlin")
  (locale "en_US.utf8")

  ;; This is where user accounts are specified.  The "root" account is
  ;; implicit, and is initially created with the empty password.
  (users (cons (user-account
                (name "alice")
                (comment "Bob's sister")
                (group "users")
                (supplementary-groups '("wheel"
                                        "audio" "video")))
               %base-user-accounts))

  ;; Globally-installed packages.
  (packages %base-packages)

  ;; Because the system will run in a Docker container, we may omit many
  ;; things that would normally be required in an operating system
  ;; configuration file.  These things include:
  ;;
  ;;   * bootloader
  ;;   * file-systems
  ;;   * services such as mingetty, udevd, slim, networking, dhcp
  ;;
  ;; Either these things are simply not required, or Docker provides
  ;; similar services for us.

  ;; This will be ignored.
  (bootloader (bootloader-configuration
               (bootloader grub-bootloader)
               (target "does-not-matter")))
  ;; This will be ignored, too.
  (file-systems (list (file-system
                        (device "does-not-matter")
                        (mount-point "/")
                        (type "does-not-matter"))))

  ;; Guix is all you need!
  (services (list (service guix-service-type))))


code:
;; This is an operating system configuration template
;; for a "desktop" setup without full-blown desktop
;; environments.

(use-modules (gnu) (gnu system nss))
(use-service-modules desktop)
(use-package-modules bootloaders certs ratpoison suckless wm xorg)

(operating-system
  (host-name "antelope")
  (timezone "Europe/Paris")
  (locale "en_US.utf8")

  ;; Use the UEFI variant of GRUB with the EFI System
  ;; Partition mounted on /boot/efi.
  (bootloader (bootloader-configuration
                (bootloader grub-efi-bootloader)
                (target "/boot/efi")))

  ;; Assume the target root file system is labelled "my-root",
  ;; and the EFI System Partition has UUID 1234-ABCD.
  (file-systems (append
                 (list (file-system
                         (device (file-system-label "my-root"))
                         (mount-point "/")
                         (type "ext4"))
                       (file-system
                         (device (uuid "1234-ABCD" 'fat))
                         (mount-point "/boot/efi")
                         (type "vfat")))
                 %base-file-systems))

  (users (cons (user-account
                (name "alice")
                (comment "Bob's sister")
                (group "users")
                (supplementary-groups '("wheel" "netdev"
                                        "audio" "video")))
               %base-user-accounts))

  ;; Add a bunch of window managers; we can choose one at
  ;; the log-in screen with F1.
  (packages (append (list
                     ;; window managers
                     ratpoison i3-wm i3status dmenu
                     ;; terminal emulator
                     xterm
                     ;; for HTTPS access
                     nss-certs)
                    %base-packages))

  ;; Use the "desktop" services, which include the X11
  ;; log-in service, networking with NetworkManager, and more.
  (services %desktop-services)

  ;; Allow resolution of '.local' host names with mDNS.
  (name-service-switch %mdns-host-lookup-nss))


code:
;; This is an operating system configuration for a VM image.
;; Modify it as you see fit and instantiate the changes by running:
;;
;;   guix system reconfigure /etc/config.scm
;;

(use-modules (gnu) (guix) (srfi srfi-1))
(use-service-modules desktop networking ssh xorg)
(use-package-modules bootloaders certs fonts nvi
                     package-management wget xorg)

(define vm-image-motd (plain-file "motd" "
\x1b[1;37mThis is the GNU system.  Welcome!\x1b[0m

This instance of Guix is a template for virtualized environments.
You can reconfigure the whole system by adjusting /etc/config.scm
and running:

  guix system reconfigure /etc/config.scm

Run '\x1b[1;37minfo guix\x1b[0m' to browse documentation.

\x1b[1;33mConsider setting a password for the 'root' and 'guest' \
accounts.\x1b[0m
"))

(operating-system
  (host-name "gnu")
  (timezone "Etc/UTC")
  (locale "en_US.utf8")
  (keyboard-layout (keyboard-layout "us" "altgr-intl"))

  ;; Label for the GRUB boot menu.
  (label (string-append "GNU Guix " (package-version guix)))

  (firmware '())

  ;; Below we assume /dev/vda is the VM's hard disk.
  ;; Adjust as needed.
  (bootloader (bootloader-configuration
               (bootloader grub-bootloader)
               (target "/dev/vda")
               (terminal-outputs '(console))))
  (file-systems (cons (file-system
                        (mount-point "/")
                        (device "/dev/vda1")
                        (type "ext4"))
                      %base-file-systems))

  (users (cons (user-account
                (name "guest")
                (comment "GNU Guix Live")
                (password "")                     ;no password
                (group "users")
                (supplementary-groups '("wheel" "netdev"
                                        "audio" "video")))
               %base-user-accounts))

  ;; Our /etc/sudoers file.  Since 'guest' initially has an empty password,
  ;; allow for password-less sudo.
  (sudoers-file (plain-file "sudoers" "\
root ALL=(ALL) ALL
%wheel ALL=NOPASSWD: ALL\n"))

  (packages (append (list font-bitstream-vera nss-certs nvi wget)
                    %base-packages))

  (services
   (append (list (service xfce-desktop-service-type)

                 ;; Choose SLiM, which is lighter than the default GDM.
                 (service slim-service-type
                          (slim-configuration
                           (auto-login? #t)
                           (default-user "guest")
                           (xorg-configuration
                            (xorg-configuration
                             (keyboard-layout keyboard-layout)))))

                 ;; Uncomment the line below to add an SSH server.
                 ;;(service openssh-service-type)

                 ;; Use the DHCP client service rather than NetworkManager.
                 (service dhcp-client-service-type))

           ;; Remove GDM, ModemManager, NetworkManager, and wpa-supplicant,
           ;; which don't make sense in a VM.
           (remove (lambda (service)
                     (let ((type (service-kind service)))
                       (or (memq type
                                 (list gdm-service-type
                                       wpa-supplicant-service-type
                                       cups-pk-helper-service-type
                                       network-manager-service-type
                                       modem-manager-service-type))
                           (eq? 'network-manager-applet
                                (service-type-name type)))))
                   (modify-services %desktop-services
                     (login-service-type config =>
                                         (login-configuration
                                          (inherit config)
                                          (motd vm-image-motd)))))))

  ;; Allow resolution of '.local' host names with mDNS.
  (name-service-switch %mdns-host-lookup-nss))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2020 Jakub Kądziołka <kuba@kadziolka.net>
;;; Copyright © 2020 Maxim Cournoyer <maxim.cournoyer@gmail.com>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (gnu system file-systems)
  #:use-module (ice-9 match)
  #:use-module (rnrs bytevectors)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-2)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-35)
  #:use-module (srfi srfi-9 gnu)
  #:use-module (guix records)
  #:use-module ((guix diagnostics) #:select (&fix-hint))
  #:use-module (guix i18n)
  #:use-module (gnu system uuid)
  #:re-export (uuid                               ;backward compatibility
               string->uuid
               uuid->string)
  #:export (file-system
            file-system?
            file-system-device
            file-system-device->string
            file-system-title                     ;deprecated
            file-system-mount-point
            file-system-type
            file-system-needed-for-boot?
            file-system-flags
            file-system-options
            file-system-options->alist
            alist->file-system-options

            file-system-mount?
            file-system-mount-may-fail?
            file-system-check?
            file-system-create-mount-point?
            file-system-dependencies
            file-system-location

            file-system-type-predicate
            btrfs-subvolume?
            btrfs-store-subvolume-file-name

            file-system-label
            file-system-label?
            file-system-label->string

            file-system->spec
            spec->file-system
            specification->file-system-mapping

            %pseudo-file-system-types
            %fuse-control-file-system
            %binary-format-file-system
            %debug-file-system
            %efivars-file-system
            %shared-memory-file-system
            %pseudo-terminal-file-system
            %tty-gid
            %immutable-store
            %control-groups
            %elogind-file-systems

            %base-file-systems
            %container-file-systems

            <file-system-mapping>
            file-system-mapping
            file-system-mapping?
            file-system-mapping-source
            file-system-mapping-target
            file-system-mapping-writable?

            file-system-mapping->bind-mount

            %store-mapping
            %network-configuration-files
            %network-file-mappings))

;;; Commentary:
;;;
;;; Declaring file systems to be mounted.
;;;
;;; Note: this file system is used both in the Shepherd and on the "host
;;; side", so it must not include (gnu packages …) modules.
;;;
;;; Code:

;; File system declaration.
(define-record-type* <file-system> %file-system
  make-file-system
  file-system?
  (device           file-system-device) ; string | <uuid> | <file-system-label>
  (mount-point      file-system-mount-point)      ; string
  (type             file-system-type)             ; string
  (flags            file-system-flags             ; list of symbols
                    (default '()))
  (options          file-system-options           ; string or #f
                    (default #f))
  (mount?           file-system-mount?            ; Boolean
                    (default #t))
  (mount-may-fail?  file-system-mount-may-fail?   ; Boolean
                    (default #f))
  (needed-for-boot? %file-system-needed-for-boot? ; Boolean
                    (default #f))
  (check?           file-system-check?            ; Boolean
                    (default #t))
  (create-mount-point? file-system-create-mount-point? ; Boolean
                       (default #f))
  (dependencies     file-system-dependencies      ; list of <file-system>
                    (default '()))                ; or <mapped-device>
  (location         file-system-location
                    (default (current-source-location))
                    (innate)))

;; A file system label for use in the 'device' field.
(define-record-type <file-system-label>
  (file-system-label label)
  file-system-label?
  (label file-system-label->string))

(set-record-type-printer! <file-system-label>
                          (lambda (obj port)
                            (format port "#<file-system-label ~s>"
                                    (file-system-label->string obj))))

(define-syntax report-deprecation
  (lambda (s)
    "Report the use of the now-deprecated 'title' field."
    (syntax-case s ()
      ((_ field)
       (let* ((source (syntax-source #'field))
              (file   (and source (assq-ref source 'filename)))
              (line   (and source
                           (and=> (assq-ref source 'line) 1+)))
              (column (and source (assq-ref source 'column))))
         (format (current-error-port)
                 "~a:~a:~a: warning: 'title' field is deprecated~%"
                 file line column)
         #t)))))

;; Helper for 'process-file-system-declaration'.
(define-syntax device-expression
  (syntax-rules (quote label uuid device)
    ((_ (quote label) dev)
     (file-system-label dev))
    ((_ (quote uuid) dev)
     (if (uuid? dev) dev (uuid dev)))
    ((_ (quote device) dev)
     dev)
    ((_ title dev)
     (case title
       ((label) (file-system-label dev))
       ((uuid)  (uuid dev))
       (else    dev)))))

;; Helper to interpret the now-deprecated 'title' field.  Detect forms like
;; (title 'label), remove them, and adjust the 'device' field accordingly.
;; TODO: Remove this once 'title' has been deprecated long enough.
(define-syntax process-file-system-declaration
  (syntax-rules (device title)
    ((_ () (rest ...) #f #f)                 ;no 'title' and no 'device' field
     (%file-system rest ...))
    ((_ () (rest ...) dev #f)                     ;no 'title' field
     (%file-system rest ... (device dev)))
    ((_ () (rest ...) dev titl)                   ;got a 'title' field
     (%file-system rest ...
                   (device (device-expression titl dev))))
    ((_ ((title titl) rest ...) (previous ...) dev _)
     (begin
       (report-deprecation (title titl))
       (process-file-system-declaration (rest ...)
                                        (previous ...)
                                        dev titl)))
    ((_ ((device dev) rest ...) (previous ...) _ titl)
     (process-file-system-declaration (rest ...)
                                      (previous ...)
                                      dev titl))
    ((_ (field rest ...) (previous ...) dev titl)
     (process-file-system-declaration (rest ...)
                                      (previous ... field)
                                      dev titl))))

(define-syntax-rule (file-system fields ...)
  (process-file-system-declaration (fields ...) () #f #f))

(define (file-system-title fs)                    ;deprecated
  (match (file-system-device fs)
    ((? file-system-label?) 'label)
    ((? uuid?)              'uuid)
    ((? string?)            'device)))

;; Note: This module is used both on the build side and on the host side.
;; Arrange not to pull (guix store) and (guix config) because the latter
;; differs from user to user.
(define (%store-prefix)
  "Return the store prefix."
  ;; Note: If we have (guix store database) in the search path and we do *not*
  ;; have (guix store) proper, 'resolve-module' returns an empty (guix store)
  ;; with one sub-module.
  (cond ((and=> (resolve-module '(guix store) #:ensure #f)
                (lambda (store)
                  (module-variable store '%store-prefix)))
         =>
         (lambda (variable)
           ((variable-ref variable))))
        ((getenv "NIX_STORE")
         => identity)
        (else
         "/gnu/store")))

(define %not-slash
  (char-set-complement (char-set #\/)))

(define (file-prefix? file1 file2)
  "Return #t if FILE1 denotes the name of a file that is a parent of FILE2,
where both FILE1 and FILE2 are absolute file name.  For example:

  (file-prefix? \"/gnu\" \"/gnu/store\")
  => #t

  (file-prefix? \"/gn\" \"/gnu/store\")
  => #f
"
  (and (string-prefix? "/" file1)
       (string-prefix? "/" file2)
       (let loop ((file1 (string-tokenize file1 %not-slash))
                  (file2 (string-tokenize file2 %not-slash)))
         (match file1
           (()
            #t)
           ((head1 tail1 ...)
            (match file2
              ((head2 tail2 ...)
               (and (string=? head1 head2) (loop tail1 tail2)))
              (()
               #f)))))))

(define* (file-system-device->string device #:key uuid-type)
  "Return the string representations of the DEVICE field of a <file-system>
record.  When the device is a UUID, its representation is chosen depending on
UUID-TYPE, a symbol such as 'dce or 'iso9660."
  (match device
    ((? file-system-label?)
     (file-system-label->string device))
    ((? uuid?)
     (if uuid-type
         (uuid->string (uuid-bytevector device) uuid-type)
         (uuid->string device)))
    ((? string?)
     device)))

(define (file-system-options->alist string)
  "Translate the option string format of a <file-system> record into an
association list of options or option/value pairs."
  (if string
      (let ((options (string-split string #\,)))
        (map (lambda (param)
               (let ((=index (string-index param #\=)))
                 (if =index
                     (cons (string-take param =index)
                           (string-drop param (1+ =index)))
                     param)))
             options))
      '()))

(define (alist->file-system-options options)
  "Return the string representation of OPTIONS, an association list.  The
string obtained can be used as the option field of a <file-system> record."
  (if (null? options)
      #f
      (string-join (map (match-lambda
                          ((key . value)
                           (string-append key "=" value))
                          (key
                           key))
                        options)
                   ",")))

(define (file-system-needed-for-boot? fs)
  "Return true if FS has the 'needed-for-boot?' flag set, or if it holds the
store--e.g., if FS is the root file system."
  (or (%file-system-needed-for-boot? fs)
      (and (file-prefix? (file-system-mount-point fs) (%store-prefix))
           (not (memq 'bind-mount (file-system-flags fs))))))

(define (file-system->spec fs)
  "Return a list corresponding to file-system FS that can be passed to the
initrd code."
  (match fs
    (($ <file-system> device mount-point type flags options mount?
                      mount-may-fail? needed-for-boot? check?)
     ;; Note: Add new fields towards the end for compatibility.
     (list (cond ((uuid? device)
                  `(uuid ,(uuid-type device) ,(uuid-bytevector device)))
                 ((file-system-label? device)
                  `(file-system-label ,(file-system-label->string device)))
                 (else device))
           mount-point type flags options mount-may-fail? check?))))

(define (spec->file-system sexp)
  "Deserialize SEXP, a list, to the corresponding <file-system> object."
  (match sexp
    ((device mount-point type flags options mount-may-fail? check?
             _ ...)                               ;placeholder for new fields
     (file-system
       (device (match device
                 (('uuid (? symbol? type) (? bytevector? bv))
                  (bytevector->uuid bv type))
                 (('file-system-label (? string? label))
                  (file-system-label label))
                 (_
                  device)))
       (mount-point mount-point) (type type)
       (flags flags) (options options)
       (mount-may-fail? mount-may-fail?)
       (check? check?)))))

(define (specification->file-system-mapping spec writable?)
  "Read the SPEC and return the corresponding <file-system-mapping>.  SPEC is
a string of the form \"SOURCE\" or \"SOURCE=TARGET\".  The former specifies
that SOURCE from the host should be mounted at SOURCE in the other system.
The latter format specifies that SOURCE from the host should be mounted at
TARGET in the other system."
  (let ((index (string-index spec #\=)))
    (if index
        (file-system-mapping
         (source (substring spec 0 index))
         (target (substring spec (+ 1 index)))
         (writable? writable?))
        (file-system-mapping
         (source spec)
         (target spec)
         (writable? writable?)))))

;;;
;;; Common file systems.
;;;

(define %pseudo-file-system-types
  ;; List of know pseudo file system types.  This is used when validating file
  ;; system definitions.
  '("binfmt_misc" "cgroup" "debugfs" "devpts" "devtmpfs" "efivarfs" "fusectl"
    "hugetlbfs" "overlay" "proc" "securityfs" "sysfs" "tmpfs"))

(define %fuse-control-file-system
  ;; Control file system for Linux' file systems in user-space (FUSE).
  (file-system
    (device "fusectl")
    (mount-point "/sys/fs/fuse/connections")
    (type "fusectl")
    (check? #f)))

(define %binary-format-file-system
  ;; Support for arbitrary executable binary format.
  (file-system
    (device "binfmt_misc")
    (mount-point "/proc/sys/fs/binfmt_misc")
    (type "binfmt_misc")
    (check? #f)))

(define %debug-file-system
  (file-system
    (type "debugfs")
    (device "none")
    (mount-point "/sys/kernel/debug")
    (check? #f)
    (create-mount-point? #t)))

(define %efivars-file-system
  ;; Support for EFI variables file system.
  (file-system
    (device "efivarfs")
    (mount-point "/sys/firmware/efi/efivars")
    (type "efivarfs")
    (mount-may-fail? #t)
    (needed-for-boot? #f)
    (check? #f)))

(define %tty-gid
  ;; ID of the 'tty' group.  Allocate it statically to make it easy to refer
  ;; to it from here and from the 'tty' group definitions.
  996)

(define %pseudo-terminal-file-system
  ;; The pseudo-terminal file system.  It needs to be mounted so that
  ;; statfs(2) returns DEVPTS_SUPER_MAGIC like libc's getpt(3) expects (and
  ;; thus openpty(3) and its users, such as xterm.)
  (file-system
    (device "none")
    (mount-point "/dev/pts")
    (type "devpts")
    (check? #f)
    (needed-for-boot? #f)
    (create-mount-point? #t)
    (options (string-append "gid=" (number->string %tty-gid) ",mode=620"))))

(define %shared-memory-file-system
  ;; Shared memory.
  (file-system
    (device "tmpfs")
    (mount-point "/dev/shm")
    (type "tmpfs")
    (check? #f)
    (flags '(no-suid no-dev))
    (options "size=50%")                         ;TODO: make size configurable
    (create-mount-point? #t)))

(define %immutable-store
  ;; Read-only store to avoid users or daemons accidentally modifying it.
  ;; 'guix-daemon' has provisions to remount it read-write in its own name
  ;; space.
  (file-system
    (device (%store-prefix))
    (mount-point (%store-prefix))
    (type "none")
    (check? #f)
    (flags '(read-only bind-mount no-atime))))

(define %control-groups
  (let ((parent (file-system
                  (device "cgroup")
                  (mount-point "/sys/fs/cgroup")
                  (type "tmpfs")
                  (check? #f))))
    (cons parent
          (map (lambda (subsystem)
                 (file-system
                   (device "cgroup")
                   (mount-point (string-append "/sys/fs/cgroup/" subsystem))
                   (type "cgroup")
                   (check? #f)
                   (options subsystem)
                   (create-mount-point? #t)

                   ;; This must be mounted after, and unmounted before the
                   ;; parent directory.
                   (dependencies (list parent))))
               '("cpuset" "cpu" "cpuacct" "memory" "devices" "freezer"
                 "blkio" "perf_event" "pids")))))

(define %elogind-file-systems
  ;; We don't use systemd, but these file systems are needed for elogind,
  ;; which was extracted from systemd.
  (append
   (list (file-system
           (device "none")
           (mount-point "/run/systemd")
           (type "tmpfs")
           (check? #f)
           (flags '(no-suid no-dev no-exec))
           (options "mode=0755")
           (create-mount-point? #t))
         (file-system
           (device "none")
           (mount-point "/run/user")
           (type "tmpfs")
           (check? #f)
           (flags '(no-suid no-dev no-exec))
           (options "mode=0755")
           (create-mount-point? #t))
         ;; Elogind uses cgroups to organize processes, allowing it to map PIDs
         ;; to sessions.  Elogind's cgroup hierarchy isn't associated with any
         ;; resource controller ("subsystem").
         (file-system
           (device "cgroup")
           (mount-point "/sys/fs/cgroup/elogind")
           (type "cgroup")
           (check? #f)
           (options "none,name=elogind")
           (create-mount-point? #t)
           (dependencies (list (car %control-groups)))))
   %control-groups))

(define %base-file-systems
  ;; List of basic file systems to be mounted.  Note that /proc and /sys are
  ;; currently mounted by the initrd.
  (list %pseudo-terminal-file-system
        %debug-file-system
        %shared-memory-file-system
        %efivars-file-system
        %immutable-store))

;; File systems for Linux containers differ from %base-file-systems in that
;; they impose additional restrictions such as no-exec or need different
;; options to function properly.
;;
;; The file system flags and options conform to the libcontainer
;; specification:
;; https://github.com/docker/libcontainer/blob/master/SPEC.md#filesystem
(define %container-file-systems
  (list
   ;; Pseudo-terminal file system.
   (file-system
     (device "none")
     (mount-point "/dev/pts")
     (type "devpts")
     (flags '(no-exec no-suid))
     (needed-for-boot? #t)
     (create-mount-point? #t)
     (check? #f)
     (options "newinstance,ptmxmode=0666,mode=620"))
   ;; Shared memory file system.
   (file-system
     (device "tmpfs")
     (mount-point "/dev/shm")
     (type "tmpfs")
     (flags '(no-exec no-suid no-dev))
     (options "mode=1777,size=65536k")
     (needed-for-boot? #t)
     (create-mount-point? #t)
     (check? #f))
   ;; Message queue file system.
   (file-system
     (device "mqueue")
     (mount-point "/dev/mqueue")
     (type "mqueue")
     (flags '(no-exec no-suid no-dev))
     (needed-for-boot? #t)
     (create-mount-point? #t)
     (check? #f))))

;;;
;;; Shared file systems, for VMs/containers.
;;;

;; Mapping of host file system SOURCE to mount point TARGET in the guest.
(define-record-type* <file-system-mapping> file-system-mapping
  make-file-system-mapping
  file-system-mapping?
  (source    file-system-mapping-source)          ;string
  (target    file-system-mapping-target)          ;string
  (writable? file-system-mapping-writable?        ;Boolean
             (default #f)))

(define (file-system-mapping->bind-mount mapping)
  "Return a file system that realizes MAPPING, a <file-system-mapping>, using
a bind mount."
  (match mapping
    (($ <file-system-mapping> source target writable?)
     (file-system
       (mount-point target)
       (device source)
       (type "none")
       (flags (if writable?
                  '(bind-mount)
                  '(bind-mount read-only)))
       (check? #f)
       (create-mount-point? #t)))))

(define %store-mapping
  ;; Mapping of the host's store into the guest.
  (file-system-mapping
   (source (%store-prefix))
   (target (%store-prefix))
   (writable? #f)))

(define %network-configuration-files
  ;; List of essential network configuration files.
  '("/etc/resolv.conf"
    "/etc/nsswitch.conf"
    "/etc/services"
    "/etc/hosts"))

(define %network-file-mappings
  ;; List of file mappings for essential network files.
  (filter-map (lambda (file)
                (file-system-mapping
                 (source file)
                 (target file)
                 ;; XXX: On some GNU/Linux systems, /etc/resolv.conf is a
                 ;; symlink to a file in a tmpfs which, for an unknown reason,
                 ;; cannot be bind mounted read-only within the container.
                 ;; The same goes with /var/run/nscd, as discussed in
                 ;; <https://bugs.gnu.org/37967>.
                 (writable? (or (string=? file "/etc/resolv.conf")
                                (string=? file "/var/run/nscd")))))
              (cons "/var/run/nscd" %network-configuration-files)))

(define (file-system-type-predicate type)
  "Return a predicate that, when passed a file system, returns #t if that file
system has the given TYPE."
  (lambda (fs)
    (string=? (file-system-type fs) type)))

;;;
;;; Btrfs specific helpers.
;;;

(define (btrfs-subvolume? fs)
  "Predicate to check if FS, a file-system object, is a Btrfs subvolume."
  (and-let* ((btrfs-file-system? (string= "btrfs" (file-system-type fs)))
             (option-keys (map (match-lambda
                                 ((key . value) key)
                                 (key key))
                               (file-system-options->alist
                                (file-system-options fs)))))
    (find (cut string-prefix? "subvol" <>) option-keys)))

(define (btrfs-store-subvolume-file-name file-systems)
  "Return the subvolume file name within the Btrfs top level onto which the
store is located, else #f."

  (define (prepend-slash/maybe s)
    (if (string=? "/" (string-take s 1))
        s
        (string-append "/" s)))

  (define (file-name-depth file-name)
    (length (string-tokenize file-name %not-slash)))

  (and-let* ((btrfs-subvolume-fs (filter btrfs-subvolume? file-systems))
             (btrfs-subvolume-fs*
              (sort btrfs-subvolume-fs
                    (lambda (fs1 fs2)
                      (> (file-name-depth (file-system-mount-point fs1))
                         (file-name-depth (file-system-mount-point fs2))))))
             (store-subvolume-fs
              (find (lambda (fs) (file-prefix? (file-system-mount-point fs)
                                               (%store-prefix)))
                    btrfs-subvolume-fs*))
             (options (file-system-options->alist
                       (file-system-options store-subvolume-fs))))
    ;; XXX: Deriving the subvolume name based from a subvolume ID is not
    ;; supported, as we'd need to query the actual file system.
    (or (and=> (assoc-ref options "subvol") prepend-slash/maybe)
        (raise (condition
                (&message
                 (message "The store is on a Btrfs subvolume, but the \
subvolume name is unknown."))
                (&fix-hint
                 (hint
                  (G_ "Use the @code{subvol} Btrfs file system option."))))))))

;;; file-systems.scm ends here


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2020 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2020 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (gnu system hurd)
  #:use-module (guix gexp)
  #:use-module (guix profiles)
  #:use-module (guix utils)
  #:use-module (gnu bootloader)
  #:use-module (gnu bootloader grub)
  #:use-module (gnu packages admin)
  #:use-module (gnu packages base)
  #:use-module (gnu packages bash)
  #:use-module (gnu packages cross-base)
  #:use-module (gnu packages file)
  #:use-module (gnu packages guile)
  #:use-module (gnu packages guile-xyz)
  #:use-module (gnu packages hurd)
  #:use-module (gnu packages less)
  #:use-module (gnu services)
  #:use-module (gnu services base)
  #:use-module (gnu services hurd)
  #:use-module (gnu services shepherd)
  #:use-module (gnu system)
  #:use-module (gnu system shadow)
  #:use-module (gnu system vm)
  #:export (%base-packages/hurd
            %base-services/hurd
            %hurd-default-operating-system
            %hurd-default-operating-system-kernel))

;;; Commentary:
;;;
;;; This module provides system-specifics for the GNU/Hurd operating system
;;; and virtual machine.
;;;
;;; Code:

(define %hurd-default-operating-system-kernel
  (if (hurd-system?)
      gnumach
      ;; A cross-built GNUmach does not work
      (with-parameters ((%current-system "i686-linux")
                        (%current-target-system #f))
        gnumach)))

(define %base-packages/hurd
  (list hurd bash coreutils file findutils grep sed
        guile-3.0 guile-colorized guile-readline
        net-base inetutils less shepherd which))

(define %base-services/hurd
  (list (service hurd-console-service-type
                 (hurd-console-configuration (hurd hurd)))
        (service hurd-getty-service-type (hurd-getty-configuration
                                          (tty "tty1")))
        (service hurd-getty-service-type (hurd-getty-configuration
                                          (tty "tty2")))
        (service static-networking-service-type
                 (list (static-networking (interface "lo")
                                          (ip "127.0.0.1")
                                          (requirement '())
                                          (provision '(loopback))
                                          (name-servers '("10.0.2.3")))))
        (syslog-service)
        (service guix-service-type
                 (guix-configuration
                  (extra-options '("--disable-chroot"
                                   "--disable-deduplication"))))
        (service special-files-service-type
                 `(("/bin/sh" ,(file-append bash "/bin/sh"))
                   ("/usr/bin/env" ,(file-append coreutils "/bin/env"))))))

(define %hurd-default-operating-system
  (operating-system
    (kernel %hurd-default-operating-system-kernel)
    (kernel-arguments '())
    (hurd hurd)
    (bootloader (bootloader-configuration
                 (bootloader grub-minimal-bootloader)
                 (target "/dev/vda")))
    (initrd #f)
    (initrd-modules (lambda _ '()))
    (firmware '())
    (host-name "guixygnu")
    (file-systems '())
    (packages %base-packages/hurd)
    (timezone "GNUrope")
    (name-service-switch #f)
    (essential-services (hurd-default-essential-services this-operating-system))
    (pam-services '())
    (setuid-programs '())
    (sudoers-file #f)))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2020 Mathieu Othacehe <m.othacehe@gmail.com>
;;; Copyright © 2020 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (gnu system image)
  #:use-module (guix gexp)
  #:use-module (guix modules)
  #:use-module (guix monads)
  #:use-module (guix records)
  #:use-module (guix store)
  #:use-module (guix ui)
  #:use-module (guix utils)
  #:use-module ((guix self) #:select (make-config.scm))
  #:use-module (gnu bootloader)
  #:use-module (gnu bootloader grub)
  #:use-module (gnu image)
  #:use-module (gnu services)
  #:use-module (gnu services base)
  #:use-module (gnu system)
  #:use-module (gnu system file-systems)
  #:use-module (gnu system uuid)
  #:use-module (gnu system vm)
  #:use-module (guix packages)
  #:use-module (gnu packages base)
  #:use-module (gnu packages bootloaders)
  #:use-module (gnu packages cdrom)
  #:use-module (gnu packages disk)
  #:use-module (gnu packages gawk)
  #:use-module (gnu packages genimage)
  #:use-module (gnu packages guile)
  #:autoload   (gnu packages gnupg) (guile-gcrypt)
  #:use-module (gnu packages hurd)
  #:use-module (gnu packages linux)
  #:use-module (gnu packages mtools)
  #:use-module ((srfi srfi-1) #:prefix srfi-1:)
  #:use-module (srfi srfi-11)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-35)
  #:use-module (rnrs bytevectors)
  #:use-module (ice-9 match)
  #:export (root-offset
            root-label

            esp-partition
            root-partition

            efi-disk-image
            iso9660-image

            find-image
            system-image
            image-with-label))

;;;
;;; Images definitions.
;;;

;; This is the offset before the first partition. GRUB will install itself in
;; this post-MBR gap.
(define root-offset (* 512 2048))

;; Generic root partition label.
(define root-label "Guix_image")

(define esp-partition
  (partition
   (size (* 40 (expt 2 20)))
   (offset root-offset)
   (label "GNU-ESP") ;cosmetic only
   ;; Use "vfat" here since this property is used when mounting.  The actual
   ;; FAT-ness is based on file system size (16 in this case).
   (file-system "vfat")
   (flags '(esp))
   (initializer (gexp initialize-efi-partition))))

(define root-partition
  (partition
   (size 'guess)
   (label root-label)
   (file-system "ext4")
   (flags '(boot))
   (initializer (gexp initialize-root-partition))))

(define efi-disk-image
  (image
   (format 'disk-image)
   (partitions (list esp-partition root-partition))))

(define iso9660-image
  (image
   (format 'iso9660)
   (partitions
    (list (partition
           (size 'guess)
           (label "GUIX_IMAGE")
           (flags '(boot)))))))

;;
;; Helpers.
;;

(define not-config?
  ;; Select (guix …) and (gnu …) modules, except (guix config).
  (match-lambda
    (('guix 'config) #f)
    (('guix rest ...) #t)
    (('gnu rest ...) #t)
    (rest #f)))

(define (partition->gexp partition)
  "Turn PARTITION, a <partition> object, into a list-valued gexp suitable for
'make-partition-image'."
  #~'(#$@(list (partition-size partition))
      #$(partition-file-system partition)
      #$(partition-file-system-options partition)
      #$(partition-label partition)
      #$(and=> (partition-uuid partition)
               uuid-bytevector)))

(define gcrypt-sqlite3&co
  ;; Guile-Gcrypt, Guile-SQLite3, and their propagated inputs.
  (srfi-1:append-map
   (lambda (package)
     (cons package
           (match (package-transitive-propagated-inputs package)
             (((labels packages) ...)
              packages))))
   (list guile-gcrypt guile-sqlite3)))

(define-syntax-rule (with-imported-modules* gexp* ...)
  (with-extensions gcrypt-sqlite3&co
    (with-imported-modules `(,@(source-module-closure
                                '((gnu build vm)
                                  (gnu build image)
                                  (gnu build hurd-boot)
                                  (gnu build linux-boot)
                                  (guix store database))
                                #:select? not-config?)
                             ((guix config) => ,(make-config.scm)))
      #~(begin
          (use-modules (gnu build vm)
                       (gnu build image)
                       (gnu build hurd-boot)
                       (gnu build linux-boot)
                       (guix store database)
                       (guix build utils))
          gexp* ...))))

(define (root-partition? partition)
  "Return true if PARTITION is the root partition, false otherwise."
  (member 'boot (partition-flags partition)))

(define (find-root-partition image)
  "Return the root partition of the given IMAGE."
  (srfi-1:find root-partition? (image-partitions image)))

(define (root-partition-index image)
  "Return the index of the root partition of the given IMAGE."
  (1+ (srfi-1:list-index root-partition? (image-partitions image))))

;;
;; Disk image.
;;

(define* (system-disk-image image
                            #:key
                            (name "disk-image")
                            bootcfg
                            bootloader
                            register-closures?
                            (inputs '()))
  "Return as a file-like object, the disk-image described by IMAGE.  Said
image can be copied on a USB stick as is.  BOOTLOADER is the bootloader that
will be installed and configured according to BOOTCFG parameter.

Raw images of the IMAGE partitions are first created.  Then, genimage is used
to assemble the partition images into a disk-image without resorting to a
virtual machine.

INPUTS is a list of inputs (as for packages).  When REGISTER-CLOSURES? is
true, register INPUTS in the store database of the image so that Guix can be
used in the image."

  (define genimage-name "image")

  (define (image->genimage-cfg image)
    ;; Return as a file-like object, the genimage configuration file
    ;; describing the given IMAGE.
    (define (format->image-type format)
      ;; Return the genimage format corresponding to FORMAT.  For now, only
      ;; the hdimage format (raw disk-image) is supported.
      (case format
        ((disk-image) "hdimage")
        (else
         (raise (condition
                 (&message
                  (message
                   (format #f (G_ "Unsupported image type ~a~%.") format))))))))

    (define (partition->dos-type partition)
      ;; Return the MBR partition type corresponding to the given PARTITION.
      ;; See: https://en.wikipedia.org/wiki/Partition_type.
      (let ((flags (partition-flags partition)))
        (cond
         ((member 'esp flags) "0xEF")
         (else "0x83"))))

    (define (partition-image partition)
      ;; Return as a file-like object, an image of the given PARTITION.  A
      ;; directory, filled by calling the PARTITION initializer procedure, is
      ;; first created within the store.  Then, an image of this directory is
      ;; created using tools such as 'mke2fs' or 'mkdosfs', depending on the
      ;; partition file-system type.
      (let* ((os (image-operating-system image))
             (schema (local-file (search-path %load-path
                                              "guix/store/schema.sql")))
             (graph (match inputs
                      (((names . _) ...)
                       names)))
             (type (partition-file-system partition))
             (image-builder
              (with-imported-modules*
               (let ((initializer #$(partition-initializer partition))
                     (inputs '#+(list e2fsprogs fakeroot dosfstools mtools))
                     (image-root "tmp-root"))
                 (sql-schema #$schema)

                 (set-path-environment-variable "PATH" '("bin" "sbin") inputs)

                 ;; Allow non-ASCII file names--e.g., 'nss-certs'--to be
                 ;; decoded.
                 (setenv "GUIX_LOCPATH"
                         #+(file-append glibc-utf8-locales "/lib/locale"))
                 (setlocale LC_ALL "en_US.utf8")

                 (initializer image-root
                              #:references-graphs '#$graph
                              #:deduplicate? #f
                              #:system-directory #$os
                              #:grub-efi #+grub-efi
                              #:bootloader-package
                              #+(bootloader-package bootloader)
                              #:bootloader-installer
                              #+(bootloader-installer bootloader)
                              #:bootcfg #$bootcfg
                              #:bootcfg-location
                              #$(bootloader-configuration-file bootloader))
                 (make-partition-image #$(partition->gexp partition)
                                       #$output
                                       image-root)))))
        (computed-file "partition.img" image-builder
                       #:options `(#:references-graphs ,inputs))))

    (define (partition->config partition)
      ;; Return the genimage partition configuration for PARTITION.
      (let ((label (partition-label partition))
            (dos-type (partition->dos-type partition))
            (image (partition-image partition))
            (offset (partition-offset partition)))
        #~(format #f "~/partition ~a {
~/~/partition-type = ~a
~/~/image = \"~a\"
~/~/offset = \"~a\"
~/}"
                  #$label
                  #$dos-type
                  #$image
                  #$offset)))

    (let* ((format (image-format image))
           (image-type (format->image-type format))
           (partitions (image-partitions image))
           (partitions-config (map partition->config partitions))
           (builder
            #~(begin
                (let ((format (@ (ice-9 format) format)))
                  (call-with-output-file #$output
                    (lambda (port)
                      (format port
                              "\
image ~a {
~/~a {}
~{~a~^~%~}
}~%" #$genimage-name #$image-type (list #$@partitions-config))))))))
      (computed-file "genimage.cfg" builder)))

  (let* ((image-name (image-name image))
         (name (if image-name
                   (symbol->string image-name)
                   name))
         (substitutable? (image-substitutable? image))
         (builder
          (with-imported-modules*
           (let ((inputs '#+(list genimage coreutils findutils))
                 (bootloader-installer
                  #+(bootloader-disk-image-installer bootloader)))
             (set-path-environment-variable "PATH" '("bin" "sbin") inputs)
             (genimage #$(image->genimage-cfg image) #$output)
             ;; Install the bootloader directly on the disk-image.
             (when bootloader-installer
               (bootloader-installer
                #+(bootloader-package bootloader)
                #$(root-partition-index image)
                (string-append #$output "/" #$genimage-name))))))
         (image-dir (computed-file "image-dir" builder)))
    (computed-file name
                   #~(symlink
                      (string-append #$image-dir "/" #$genimage-name)
                      #$output)
                   #:options `(#:substitutable? ,substitutable?))))

;;
;; ISO9660 image.
;;

(define (has-guix-service-type? os)
  "Return true if OS contains a service of the type GUIX-SERVICE-TYPE."
  (not (not (srfi-1:find (lambda (service)
                           (eq? (service-kind service) guix-service-type))
                         (operating-system-services os)))))

(define* (system-iso9660-image image
                               #:key
                               (name "iso9660-image")
                               bootcfg
                               bootloader
                               register-closures?
                               (inputs '())
                               (grub-mkrescue-environment '()))
  "Return as a file-like object a bootable, stand-alone iso9660 image.

INPUTS is a list of inputs (as for packages).  When REGISTER-CLOSURES? is
true, register INPUTS in the store database of the image so that Guix can be
used in the image. "
  (define root-label
    (match (image-partitions image)
      ((partition)
       (partition-label partition))))

  (define root-uuid
    (match (image-partitions image)
      ((partition)
       (uuid-bytevector (partition-uuid partition)))))

  (let* ((os (image-operating-system image))
         (bootloader (bootloader-package bootloader))
         (compression? (image-compression? image))
         (substitutable? (image-substitutable? image))
         (schema (local-file (search-path %load-path
                                          "guix/store/schema.sql")))
         (graph (match inputs
                  (((names . _) ...)
                   names)))
         (builder
          (with-imported-modules*
           (let* ((inputs '#$(list parted e2fsprogs dosfstools xorriso
                                   sed grep coreutils findutils gawk))
                  (image-root "tmp-root"))
             (sql-schema #$schema)

             ;; Allow non-ASCII file names--e.g., 'nss-certs'--to be decoded.
             (setenv "GUIX_LOCPATH"
                     #+(file-append glibc-utf8-locales "/lib/locale"))

             (setlocale LC_ALL "en_US.utf8")

             (set-path-environment-variable "PATH" '("bin" "sbin") inputs)

             (initialize-root-partition image-root
                                        #:references-graphs '#$graph
                                        #:deduplicate? #f
                                        #:system-directory #$os)
             (make-iso9660-image #$xorriso
                                 '#$grub-mkrescue-environment
                                 #$bootloader
                                 #$bootcfg
                                 #$os
                                 image-root
                                 #$output
                                 #:references-graphs '#$graph
                                 #:register-closures? #$register-closures?
                                 #:compression? #$compression?
                                 #:volume-id #$root-label
                                 #:volume-uuid #$root-uuid)))))
    (computed-file name builder
                   #:options `(#:references-graphs ,inputs
                               #:substitutable? ,substitutable?))))

(define (image-with-label base-image label)
  "The volume ID of an ISO is the label of the first partition.  This procedure
returns an image record where the first partition's label is set to <label>."
  (image
    (inherit base-image)
    (partitions
      (match (image-partitions base-image)
        ((boot others ...)
         (cons
           (partition
             (inherit boot)
             (label label))
           others))))))

;;
;; Image creation.
;;

(define (image->root-file-system image)
  "Return the IMAGE root partition file-system type."
  (let ((format (image-format image)))
    (if (eq? format 'iso9660)
        "iso9660"
        (partition-file-system (find-root-partition image)))))

(define (root-size image)
  "Return the root partition size of IMAGE."
  (let* ((image-size (image-size image))
         (root-partition (find-root-partition image))
         (root-size (partition-size root-partition)))
    (cond
     ((and (eq? root-size 'guess) image-size)
      image-size)
     (else root-size))))

(define* (image-with-os base-image os)
  "Return an image based on BASE-IMAGE but with the operating-system field set
to OS.  Also set the UUID and the size of the root partition."
  (define root-file-system
    (srfi-1:find
     (lambda (fs)
       (string=? (file-system-mount-point fs) "/"))
     (operating-system-file-systems os)))

  (image
   (inherit base-image)
   (operating-system os)
   (partitions
    (map (lambda (p)
           (if (root-partition? p)
               (partition
                (inherit p)
                (uuid (file-system-device root-file-system))
                (size (root-size base-image)))
               p))
         (image-partitions base-image)))))

(define (operating-system-for-image image)
  "Return an operating-system based on the one specified in IMAGE, but
suitable for image creation.  Assign an UUID to the root file-system, so that
it can be used for bootloading."
  (define volatile-root? (image-volatile-root? image))

  (define (root-uuid os)
    ;; UUID of the root file system, computed in a deterministic fashion.
    ;; This is what we use to locate the root file system so it has to be
    ;; different from the user's own file system UUIDs.
    (let ((type (if (eq? (image-format image) 'iso9660)
                    'iso9660
                    'dce)))
      (operating-system-uuid os type)))

  (let* ((root-file-system-type (image->root-file-system image))
         (base-os (image-operating-system image))
         (file-systems-to-keep
          (srfi-1:remove
           (lambda (fs)
             (string=? (file-system-mount-point fs) "/"))
           (operating-system-file-systems base-os)))
         (format (image-format image))
         (os
          (operating-system
            (inherit base-os)
            (initrd (lambda (file-systems . rest)
                      (apply (operating-system-initrd base-os)
                             file-systems
                             #:volatile-root? volatile-root?
                             rest)))
            (bootloader (if (eq? format 'iso9660)
                            (bootloader-configuration
                             (inherit
                              (operating-system-bootloader base-os))
                             (bootloader grub-mkrescue-bootloader))
                            (operating-system-bootloader base-os)))
            (file-systems (cons (file-system
                                  (mount-point "/")
                                  (device "/dev/placeholder")
                                  (type root-file-system-type))
                                file-systems-to-keep))))
         (uuid (root-uuid os)))
    (operating-system
      (inherit os)
      (file-systems (cons (file-system
                            (mount-point "/")
                            (device uuid)
                            (type root-file-system-type))
                          file-systems-to-keep)))))

(define* (system-image image)
  "Return the derivation of IMAGE.  It can be a raw disk-image or an ISO9660
image, depending on IMAGE format."
  (define substitutable? (image-substitutable? image))
  (define target (image-target image))

  (with-parameters ((%current-target-system target))
    (let* ((os (operating-system-for-image image))
           (image* (image-with-os image os))
           (register-closures? (has-guix-service-type? os))
           (bootcfg (operating-system-bootcfg os))
           (bootloader (bootloader-configuration-bootloader
                        (operating-system-bootloader os))))
      (case (image-format image)
        ((disk-image)
         (system-disk-image image*
                            #:bootcfg bootcfg
                            #:bootloader bootloader
                            #:register-closures? register-closures?
                            #:inputs `(("system" ,os)
                                       ("bootcfg" ,bootcfg))))
        ((iso9660)
         (system-iso9660-image
          image*
          #:bootcfg bootcfg
          #:bootloader bootloader
          #:register-closures? register-closures?
          #:inputs `(("system" ,os)
                     ("bootcfg" ,bootcfg))
          ;; Make sure to use a mode that does no imply
          ;; HFS+ tree creation that may fail with:
          ;;
          ;; "libisofs: FAILURE : Too much files to mangle,
          ;; cannot guarantee unique file names"
          ;;
          ;; This happens if some limits are exceeded, see:
          ;; https://lists.gnu.org/archive/html/grub-devel/2020-06/msg00048.html
          #:grub-mkrescue-environment
          '(("MKRESCUE_SED_MODE" . "mbr_only"))))))))

(define (find-image file-system-type target)
  "Find and return an image built that could match the given FILE-SYSTEM-TYPE,
built for TARGET.  This is useful to adapt to interfaces written before the
addition of the <image> record."
  (match file-system-type
    ("iso9660" iso9660-image)
    (_ (cond
        ((and target
              (hurd-triplet? target))
         (module-ref (resolve-interface '(gnu system images hurd))
                     'hurd-disk-image))
        (else
         efi-disk-image)))))

;;; image.scm ends here


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2020 Mathieu Othacehe <m.othacehe@gmail.com>
;;; Copyright © 2020 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (gnu system images hurd)
  #:use-module (guix gexp)
  #:use-module (gnu bootloader)
  #:use-module (gnu bootloader grub)
  #:use-module (gnu image)
  #:use-module (gnu packages ssh)
  #:use-module (gnu services)
  #:use-module (gnu services ssh)
  #:use-module (gnu system)
  #:use-module (gnu system file-systems)
  #:use-module (gnu system hurd)
  #:use-module (gnu system image)
  #:export (hurd-barebones-os
            hurd-disk-image
            hurd-barebones-disk-image))

(define hurd-barebones-os
  (operating-system
    (inherit %hurd-default-operating-system)
    (bootloader (bootloader-configuration
                 (bootloader grub-minimal-bootloader)
                 (target "/dev/sdX")))
    (file-systems (cons (file-system
                          (device (file-system-label "my-root"))
                          (mount-point "/")
                          (type "ext2"))
                        %base-file-systems))
    (host-name "guixygnu")
    (timezone "Europe/Amsterdam")
    (packages (cons openssh-sans-x %base-packages/hurd))
    (services (cons (service openssh-service-type
                             (openssh-configuration
                              (openssh openssh-sans-x)
                              (use-pam? #f)
                              (port-number 2222)
                              (permit-root-login #t)
                              (allow-empty-passwords? #t)
                              (password-authentication? #t)))
               %base-services/hurd))))

(define hurd-initialize-root-partition
  #~(lambda* (#:rest args)
      (apply initialize-root-partition
             (append args
                     (list #:make-device-nodes make-hurd-device-nodes
                           ;; XXX Creating a db.sqlite with journal_mode=WAL
                           ;; yields "unable to open database file" on GNU/Hurd
                           ;; for an sqlite with the hurd-locking-mode.patch;
                           ;; see <https://bugs.gnu.org/42151>.
                           #:wal-mode? #f)))))

(define hurd-disk-image
  (image
   (format 'disk-image)
   (target "i586-pc-gnu")
   (partitions
    (list (partition
           (size 'guess)
           (offset root-offset)
           (label root-label)
           (file-system "ext2")
           (file-system-options '("-o" "hurd" "-O" "ext_attr"))
           (flags '(boot))
           (initializer hurd-initialize-root-partition))))))

(define hurd-barebones-disk-image
  (image
   (inherit hurd-disk-image)
   (name 'hurd-barebones-disk-image)
   (operating-system hurd-barebones-os)))