code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2019 Jakob L. Kreuze <zerodaysfordays@sdf.org>
;;; Copyright © 2020 Brice Waegeneire <brice@waegenei.re>
;;;
;;; 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 machine digital-ocean)
  #:use-module (gnu machine ssh)
  #:use-module (gnu machine)
  #:use-module (gnu services)
  #:use-module (gnu services networking)
  #:use-module (gnu system)
  #:use-module (gnu system pam)
  #:use-module (guix base32)
  #:use-module (guix derivations)
  #:use-module (guix i18n)
  #:use-module ((guix diagnostics) #:select (formatted-message))
  #:use-module (guix import json)
  #:use-module (guix monads)
  #:use-module (guix records)
  #:use-module (guix ssh)
  #:use-module (guix store)
  #:use-module (ice-9 iconv)
  #:use-module (json)
  #:use-module (rnrs bytevectors)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-2)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module (ssh key)
  #:use-module (ssh sftp)
  #:use-module (ssh shell)
  #:use-module (web client)
  #:use-module (web request)
  #:use-module (web response)
  #:use-module (web uri)
  #:export (digital-ocean-configuration
            digital-ocean-configuration?

            digital-ocean-configuration-ssh-key
            digital-ocean-configuration-tags
            digital-ocean-configuration-region
            digital-ocean-configuration-size
            digital-ocean-configuration-enable-ipv6?

            digital-ocean-environment-type))

;;; Commentary:
;;;
;;; This module implements a high-level interface for provisioning "droplets"
;;; from the Digital Ocean virtual private server (VPS) service.
;;;
;;; Code:

(define %api-base "https://api.digitalocean.com")

(define %digital-ocean-token
  (make-parameter (getenv "GUIX_DIGITAL_OCEAN_TOKEN")))

(define* (post-endpoint endpoint body)
  "Encode BODY as JSON and send it to the Digital Ocean API endpoint
ENDPOINT. This procedure is quite a bit more specialized than 'http-post', as
it takes care to set headers such as 'Content-Type', 'Content-Length', and
'Authorization' appropriately."
  (let* ((uri (string->uri (string-append %api-base endpoint)))
         (body (string->bytevector (scm->json-string body) "UTF-8"))
         (headers `((User-Agent . "Guix Deploy")
                    (Accept . "application/json")
                    (Content-Type . "application/json")
                    (Authorization . ,(format #f "Bearer ~a"
                                              (%digital-ocean-token)))
                    (Content-Length . ,(number->string
                                        (bytevector-length body)))))
         (port (open-socket-for-uri uri))
         (request (build-request uri
                                 #:method 'POST
                                 #:version '(1 . 1)
                                 #:headers headers
                                 #:port port))
         (request (write-request request port)))
    (write-request-body request body)
    (force-output (request-port request))
    (let* ((response (read-response port))
           (body (read-response-body response)))
      (unless (= 2 (floor/ (response-code response) 100))
        (raise
         (condition (&message
                     (message (format
                               #f
                               (G_ "~a: HTTP post failed: ~a (~s)")
                               (uri->string uri)
                               (response-code response)
                               (response-reason-phrase response)))))))
      (close-port port)
      (bytevector->string body "UTF-8"))))

(define (fetch-endpoint endpoint)
  "Return the contents of the Digital Ocean API endpoint ENDPOINT as an
alist. This procedure is quite a bit more specialized than 'json-fetch', as it
takes care to set headers such as 'Accept' and 'Authorization' appropriately."
  (define headers
    `((user-agent . "Guix Deploy")
      (Accept . "application/json")
      (Authorization . ,(format #f "Bearer ~a" (%digital-ocean-token)))))
  (json-fetch (string-append %api-base endpoint) #:headers headers))

;;;
;;; Parameters for droplet creation.
;;;

(define-record-type* <digital-ocean-configuration> digital-ocean-configuration
  make-digital-ocean-configuration
  digital-ocean-configuration?
  this-digital-ocean-configuration
  (ssh-key     digital-ocean-configuration-ssh-key)      ; string
  (tags        digital-ocean-configuration-tags)         ; list of strings
  (region      digital-ocean-configuration-region)       ; string
  (size        digital-ocean-configuration-size)         ; string
  (enable-ipv6? digital-ocean-configuration-enable-ipv6?)) ; boolean

(define (read-key-fingerprint file-name)
  "Read the private key at FILE-NAME and return the key's fingerprint as a hex
string."
  (let* ((privkey (private-key-from-file file-name))
         (pubkey (private-key->public-key privkey))
         (hash (get-public-key-hash pubkey 'md5)))
    (bytevector->hex-string hash)))

(define (machine-droplet machine)
  "Return an alist describing the droplet allocated to MACHINE."
  (let ((tags (digital-ocean-configuration-tags
               (machine-configuration machine))))
    (find (lambda (droplet)
            (equal? (assoc-ref droplet "tags") (list->vector tags)))
          (vector->list
           (assoc-ref (fetch-endpoint "/v2/droplets") "droplets")))))

(define (machine-public-ipv4-network machine)
  "Return the public IPv4 network interface of the droplet allocated to
MACHINE as an alist. The expected fields are 'ip_address', 'netmask', and
'gateway'."
  (and-let* ((droplet (machine-droplet machine))
             (networks (assoc-ref droplet "networks"))
             (network (find (lambda (network)
                              (string= "public" (assoc-ref network "type")))
                            (vector->list (assoc-ref networks "v4")))))
    network))

;;;
;;; Remote evaluation.
;;;

(define (digital-ocean-remote-eval target exp)
  "Internal implementation of 'machine-remote-eval' for MACHINE instances with
an environment type of 'digital-ocean-environment-type'."
  (let* ((network (machine-public-ipv4-network target))
         (address (assoc-ref network "ip_address"))
         (ssh-key (digital-ocean-configuration-ssh-key
                   (machine-configuration target)))
         (delegate (machine
                    (inherit target)
                    (environment managed-host-environment-type)
                    (configuration
                     (machine-ssh-configuration
                      (host-name address)
                      (identity ssh-key)
                      (system "x86_64-linux"))))))
    (machine-remote-eval delegate exp)))

;;;
;;; System deployment.
;;;

;; The following script was adapted from the guide available at
;; <https://wiki.pantherx.org/Installation-digital-ocean/>.
(define (guix-infect network)
  "Given NETWORK, an alist describing the Droplet's public IPv4 network
interface, return a Bash script that will install the Guix system."
  (format #f "#!/bin/bash

apt-get update
apt-get install xz-utils -y
wget https://ftp.gnu.org/gnu/guix/guix-binary-1.0.1.x86_64-linux.tar.xz
cd /tmp
tar --warning=no-timestamp -xf ~~/guix-binary-1.0.1.x86_64-linux.tar.xz
mv var/guix /var/ && mv gnu /
mkdir -p ~~root/.config/guix
ln -sf /var/guix/profiles/per-user/root/current-guix ~~root/.config/guix/current
export GUIX_PROFILE=\"`echo ~~root`/.config/guix/current\" ;
source $GUIX_PROFILE/etc/profile
groupadd --system guixbuild
for i in `seq -w 1 10`; do
   useradd -g guixbuild -G guixbuild         \
           -d /var/empty -s `which nologin`  \
           -c \"Guix build user $i\" --system  \
           guixbuilder$i;
done;
cp ~~root/.config/guix/current/lib/systemd/system/guix-daemon.service /etc/systemd/system/
systemctl start guix-daemon && systemctl enable guix-daemon
mkdir -p /usr/local/bin
cd /usr/local/bin
ln -s /var/guix/profiles/per-user/root/current-guix/bin/guix
mkdir -p /usr/local/share/info
cd /usr/local/share/info
for i in /var/guix/profiles/per-user/root/current-guix/share/info/*; do
    ln -s $i;
done
guix archive --authorize < ~~root/.config/guix/current/share/guix/ci.guix.gnu.org.pub
# guix pull
guix package -i glibc-utf8-locales
export GUIX_LOCPATH=\"$HOME/.guix-profile/lib/locale\"
guix package -i openssl
cat > /etc/bootstrap-config.scm << EOF
(use-modules (gnu))
(use-service-modules networking ssh)

(operating-system
  (host-name \"gnu-bootstrap\")
  (timezone \"Etc/UTC\")
  (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))
  (services
   (append (list (static-networking-service \"eth0\" \"~a\"
                    #:netmask \"~a\"
                    #:gateway \"~a\"
                    #:name-servers '(\"84.200.69.80\" \"84.200.70.40\"))
                 (simple-service 'guile-load-path-in-global-env
                  session-environment-service-type
                  \\`((\"GUILE_LOAD_PATH\"
                     . \"/run/current-system/profile/share/guile/site/2.2\")
                    (\"GUILE_LOAD_COMPILED_PATH\"
                     . ,(string-append \"/run/current-system/profile/lib/guile/2.2/site-ccache:\"
                                       \"/run/current-system/profile/share/guile/site/2.2\"))))
                 (service openssh-service-type
                          (openssh-configuration
                           (log-level 'debug)
                           (permit-root-login 'prohibit-password))))
           %base-services)))
EOF
# guix pull
guix system build /etc/bootstrap-config.scm
guix system reconfigure /etc/bootstrap-config.scm
mv /etc /old-etc
mkdir /etc
cp -r /old-etc/{passwd,group,shadow,gshadow,mtab,guix,bootstrap-config.scm} /etc/
guix system reconfigure /etc/bootstrap-config.scm"
          (assoc-ref network "ip_address")
          (assoc-ref network "netmask")
          (assoc-ref network "gateway")))

(define (machine-wait-until-available machine)
  "Block until the initial Debian image has been installed on the droplet
named DROPLET-NAME."
  (and-let* ((droplet (machine-droplet machine))
             (droplet-id (assoc-ref droplet "id"))
             (endpoint (format #f "/v2/droplets/~a/actions" droplet-id)))
    (let loop ()
      (let ((actions (assoc-ref (fetch-endpoint endpoint) "actions")))
        (unless (every (lambda (action)
                         (string= "completed" (assoc-ref action "status")))
                       (vector->list actions))
          (sleep 5)
          (loop))))))

(define (wait-for-ssh address ssh-key)
  "Block until the an SSH session can be made as 'root' with SSH-KEY at ADDRESS."
  (let loop ()
    (catch #t
      (lambda ()
        (open-ssh-session address #:user "root" #:identity ssh-key))
      (lambda args
        (sleep 5)
        (loop)))))

(define (add-static-networking target network)
  "Return an <operating-system> based on TARGET with a static networking
configuration for the public IPv4 network described by the alist NETWORK."
  (operating-system
    (inherit (machine-operating-system target))
    (services (cons* (static-networking-service "eth0"
                        (assoc-ref network "ip_address")
                        #:netmask (assoc-ref network "netmask")
                        #:gateway (assoc-ref network "gateway")
                        #:name-servers '("84.200.69.80" "84.200.70.40"))
                    (simple-service 'guile-load-path-in-global-env
                                    session-environment-service-type
                                    `(("GUILE_LOAD_PATH"
                                       . "/run/current-system/profile/share/guile/site/2.2")
                                      ("GUILE_LOAD_COMPILED_PATH"
                                       . ,(string-append "/run/current-system/profile/lib/guile/2.2/site-ccache:"
                                                         "/run/current-system/profile/share/guile/site/2.2"))))
                    (operating-system-user-services
                     (machine-operating-system target))))))

(define (deploy-digital-ocean target)
  "Internal implementation of 'deploy-machine' for 'machine' instances with an
environment type of 'digital-ocean-environment-type'."
  (maybe-raise-missing-api-key-error)
  (maybe-raise-unsupported-configuration-error target)
  (let* ((config (machine-configuration target))
         (name (machine-display-name target))
         (region (digital-ocean-configuration-region config))
         (size (digital-ocean-configuration-size config))
         (ssh-key (digital-ocean-configuration-ssh-key config))
         (fingerprint (read-key-fingerprint ssh-key))
         (enable-ipv6? (digital-ocean-configuration-enable-ipv6? config))
         (tags (digital-ocean-configuration-tags config))
         (request-body `(("name" . ,name)
                         ("region" . ,region)
                         ("size" . ,size)
                         ("image" . "debian-9-x64")
                         ("ssh_keys" . ,(vector fingerprint))
                         ("backups" . #f)
                         ("ipv6" . ,enable-ipv6?)
                         ("user_data" . #nil)
                         ("private_networking" . #nil)
                         ("volumes" . #nil)
                         ("tags" . ,(list->vector tags))))
         (response (post-endpoint "/v2/droplets" request-body)))
    (machine-wait-until-available target)
    (let* ((network (machine-public-ipv4-network target))
           (address (assoc-ref network "ip_address")))
      (wait-for-ssh address ssh-key)
      (let* ((ssh-session (open-ssh-session address #:user "root" #:identity ssh-key))
             (sftp-session (make-sftp-session ssh-session)))
        (call-with-remote-output-file sftp-session "/tmp/guix-infect.sh"
                                      (lambda (port)
                                        (display (guix-infect network) port)))
        (rexec ssh-session "/bin/bash /tmp/guix-infect.sh")
        ;; Session will close upon rebooting, which will raise 'guile-ssh-error.
        (catch 'guile-ssh-error
          (lambda () (rexec ssh-session "reboot"))
          (lambda args #t)))
      (wait-for-ssh address ssh-key)
      (let ((delegate (machine
                       (operating-system (add-static-networking target network))
                       (environment managed-host-environment-type)
                       (configuration
                        (machine-ssh-configuration
                         (host-name address)
                         (identity ssh-key)
                         (system "x86_64-linux"))))))
        (deploy-machine delegate)))))

;;;
;;; Roll-back.
;;;

(define (roll-back-digital-ocean target)
  "Internal implementation of 'roll-back-machine' for MACHINE instances with an
environment type of 'digital-ocean-environment-type'."
  (let* ((network (machine-public-ipv4-network target))
         (address (assoc-ref network "ip_address"))
         (ssh-key (digital-ocean-configuration-ssh-key
                   (machine-configuration target)))
         (delegate (machine
                    (inherit target)
                    (environment managed-host-environment-type)
                    (configuration
                     (machine-ssh-configuration
                      (host-name address)
                      (identity ssh-key)
                      (system "x86_64-linux"))))))
    (roll-back-machine delegate)))

;;;
;;; Environment type.
;;;

(define digital-ocean-environment-type
  (environment-type
   (machine-remote-eval digital-ocean-remote-eval)
   (deploy-machine      deploy-digital-ocean)
   (roll-back-machine   roll-back-digital-ocean)
   (name                'digital-ocean-environment-type)
   (description         "Provisioning of \"droplets\": virtual machines
 provided by the Digital Ocean virtual private server (VPS) service.")))

(define (maybe-raise-missing-api-key-error)
  (unless (%digital-ocean-token)
    (raise (condition
            (&message
             (message (G_ "No Digital Ocean access token was provided. This \
may be fixed by setting the environment variable GUIX_DIGITAL_OCAEN_TOKEN to \
one procured from https://cloud.digitalocean.com/account/api/tokens.")))))))

(define (maybe-raise-unsupported-configuration-error machine)
  "Raise an error if MACHINE's configuration is not an instance of
<digital-ocean-configuration>."
  (let ((config (machine-configuration machine))
        (environment (environment-type-name (machine-environment machine))))
    (unless (and config (digital-ocean-configuration? config))
      (raise (formatted-message (G_ "unsupported machine configuration '~a' \
for environment of type '~a'")
                                config
                                environment)))))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2019 Jakob L. Kreuze <zerodaysfordays@sdf.org>
;;; Copyright © 2020, 2021 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 machine ssh)
  #:use-module (gnu bootloader)
  #:use-module (gnu machine)
  #:autoload   (gnu packages gnupg) (guile-gcrypt)
  #:use-module (gnu system)
  #:use-module (gnu system file-systems)
  #:use-module (gnu system uuid)
  #:use-module ((gnu services) #:select (sexp->system-provenance))
  #:use-module (guix diagnostics)
  #:use-module (guix gexp)
  #:use-module (guix i18n)
  #:use-module (guix modules)
  #:use-module (guix monads)
  #:use-module (guix pki)
  #:use-module (guix records)
  #:use-module (guix remote)
  #:use-module (guix scripts system reconfigure)
  #:use-module (guix ssh)
  #:use-module (guix store)
  #:use-module (guix utils)
  #:use-module ((guix self) #:select (make-config.scm))
  #:use-module ((guix inferior)
                #:select (inferior-exception?
                          inferior-exception-arguments))
  #:use-module (gcrypt pk-crypto)
  #:use-module (ice-9 format)
  #:use-module (ice-9 match)
  #:use-module (ice-9 textual-ports)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-19)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:export (managed-host-environment-type

            machine-ssh-configuration
            machine-ssh-configuration?
            machine-ssh-configuration

            machine-ssh-configuration-host-name
            machine-ssh-configuration-build-locally?
            machine-ssh-configuration-authorize?
            machine-ssh-configuration-allow-downgrades?
            machine-ssh-configuration-port
            machine-ssh-configuration-user
            machine-ssh-configuration-host-key
            machine-ssh-configuration-session))

;;; Commentary:
;;;
;;; This module implements remote evaluation and system deployment for
;;; machines that are accessible over SSH and have a known host-name. In the
;;; sense of the broader "machine" interface, we describe the environment for
;;; such machines as 'managed-host.
;;;
;;; Code:

;;;
;;; Parameters for the SSH client.
;;;

(define-record-type* <machine-ssh-configuration> machine-ssh-configuration
  make-machine-ssh-configuration
  machine-ssh-configuration?
  (host-name      machine-ssh-configuration-host-name)     ; string
  (system         machine-ssh-configuration-system)        ; string
  (build-locally? machine-ssh-configuration-build-locally? ; boolean
                  (default #t))
  (authorize?     machine-ssh-configuration-authorize?     ; boolean
                  (default #t))
  (allow-downgrades? machine-ssh-configuration-allow-downgrades? ; boolean
                     (default #f))
  (port           machine-ssh-configuration-port           ; integer
                  (default 22))
  (user           machine-ssh-configuration-user           ; string
                  (default "root"))
  (identity       machine-ssh-configuration-identity       ; path to a private key
                  (default #f))
  (session        machine-ssh-configuration-session        ; session
                  (default #f))
  (host-key       machine-ssh-configuration-host-key       ; #f | string
                  (default #f)))

(define (machine-ssh-session machine)
  "Return the SSH session that was given in MACHINE's configuration, or create
one from the configuration's parameters if one was not provided."
  (maybe-raise-unsupported-configuration-error machine)
  (let ((config (machine-configuration machine)))
    (or (machine-ssh-configuration-session config)
        (let ((host-name (machine-ssh-configuration-host-name config))
              (user (machine-ssh-configuration-user config))
              (port (machine-ssh-configuration-port config))
              (identity (machine-ssh-configuration-identity config))
              (host-key (machine-ssh-configuration-host-key config)))
          (unless host-key
            (warning (G_ "<machine-ssh-configuration> without a 'host-key' \
is deprecated~%")))
          (open-ssh-session host-name
                            #:user user
                            #:port port
                            #:identity identity
                            #:host-key host-key)))))

;;;
;;; Remote evaluation.
;;;

(define (machine-become-command machine)
  "Return as a list of strings the program and arguments necessary to run a
shell command with escalated privileges for MACHINE's configuration."
  (if (string= "root" (machine-ssh-configuration-user
                       (machine-configuration machine)))
      '()
      '("/run/setuid-programs/sudo" "-n" "--")))

(define (managed-host-remote-eval machine exp)
  "Internal implementation of 'machine-remote-eval' for MACHINE instances with
an environment type of 'managed-host."
  (maybe-raise-unsupported-configuration-error machine)
  (let ((config (machine-configuration machine)))
    (remote-eval exp (machine-ssh-session machine)
                 #:build-locally?
                 (machine-ssh-configuration-build-locally? config)
                 #:system
                 (machine-ssh-configuration-system config)
                 #:become-command
                 (machine-become-command machine))))

;;;
;;; Safety checks.
;;;

;; Assertion to be executed remotely.  This abstraction exists to allow us to
;; gather a list of expressions to be evaluated and eventually evaluate them
;; all at once instead of one by one.  (This is pretty much a monad.)
(define-record-type <remote-assertion>
  (remote-assertion exp proc)
  remote-assertion?
  (exp   remote-assertion-expression)
  (proc  remote-assertion-procedure))

(define-syntax-rule (remote-let ((var exp)) body ...)
  "Return a <remote-assertion> that binds VAR to the result of evaluating EXP,
a gexp, remotely, and evaluate BODY in that context."
  (remote-assertion exp (lambda (var) body ...)))

(define (machine-check-file-system-availability machine)
  "Return a list of <remote-assertion> that raise a '&message' error condition
if any of the file-systems specified in MACHINE's 'system' declaration do not
exist on the machine."
  (define file-systems
    (filter (lambda (fs)
              (and (file-system-mount? fs)
                   (not (member (file-system-type fs)
                                %pseudo-file-system-types))
                   ;; Don't try to validate network file systems.
                   (not (string-prefix? "nfs" (file-system-type fs)))
                   (not (memq 'bind-mount (file-system-flags fs)))))
            (operating-system-file-systems (machine-operating-system machine))))

  (define (check-literal-file-system fs)
    (remote-let ((errno #~(catch 'system-error
                            (lambda ()
                              (stat #$(file-system-device fs))
                              #t)
                            (lambda args
                              (system-error-errno args)))))
      (when (number? errno)
        (raise (formatted-message (G_ "device '~a' not found: ~a")
                                  (file-system-device fs)
                                  (strerror errno))))))

  (define (check-labeled-file-system fs)
    (define remote-exp
      (with-imported-modules (source-module-closure
                              '((gnu build file-systems)))
        #~(begin
            (use-modules (gnu build file-systems))
            (find-partition-by-label #$(file-system-label->string
                                        (file-system-device fs))))))

    (remote-let ((result remote-exp))
      (unless result
        (raise (formatted-message (G_ "no file system with label '~a'")
                                  (file-system-label->string
                                   (file-system-device fs)))))))

  (define (check-uuid-file-system fs)
    (define remote-exp
      (with-imported-modules (source-module-closure
                              '((gnu build file-systems)
                                (gnu system uuid)))
        #~(begin
            (use-modules (gnu build file-systems)
                         (gnu system uuid))

            (let ((uuid (uuid #$(uuid->string (file-system-device fs))
                              '#$(uuid-type (file-system-device fs)))))
              (find-partition-by-uuid uuid)))))

    (remote-let ((result remote-exp))
      (unless result
        (raise (formatted-message (G_ "no file system with UUID '~a'")
                                  (uuid->string (file-system-device fs)))))))

  (append (map check-literal-file-system
               (filter (lambda (fs)
                         (string? (file-system-device fs)))
                       file-systems))
          (map check-labeled-file-system
               (filter (lambda (fs)
                         (file-system-label? (file-system-device fs)))
                       file-systems))
          (map check-uuid-file-system
               (filter (lambda (fs)
                         (uuid? (file-system-device fs)))
                       file-systems))))

(define (machine-check-initrd-modules machine)
  "Return a list of <remote-assertion> that raise a '&message' error condition
if any of the modules needed by 'needed-for-boot' file systems in MACHINE are
not available in the initrd."
  (define file-systems
    (filter file-system-needed-for-boot?
            (operating-system-file-systems (machine-operating-system machine))))

  (define (missing-modules fs)
    (define remote-exp
      (let ((device (file-system-device fs)))
        (with-imported-modules (source-module-closure
                                '((gnu build file-systems)
                                  (gnu build linux-modules)
                                  (gnu system uuid)))
          #~(begin
              (use-modules (gnu build file-systems)
                           (gnu build linux-modules)
                           (gnu system uuid))

              (define dev
                #$(cond ((string? device) device)
                        ((uuid? device) #~(find-partition-by-uuid
                                           (string->uuid
                                            #$(uuid->string device))))
                        ((file-system-label? device)
                         #~(find-partition-by-label
                            #$(file-system-label->string device)))))

              (missing-modules dev '#$(operating-system-initrd-modules
                                       (machine-operating-system machine)))))))

    (remote-let ((missing remote-exp))
      (unless (null? missing)
        (raise (formatted-message (G_ "missing modules for ~a:~{ ~a~}~%")
                                  (file-system-device fs)
                                  missing)))))

  (map missing-modules file-systems))

(define* (machine-check-forward-update machine)
  "Check whether we are making a forward update for MACHINE.  Depending on its
'allow-upgrades?' field, raise an error or display a warning if we are
potentially downgrading it."
  (define config
    (machine-configuration machine))

  (define validate-reconfigure
    (if (machine-ssh-configuration-allow-downgrades? config)
        warn-about-backward-reconfigure
        ensure-forward-reconfigure))

  (remote-let ((provenance #~(call-with-input-file
                                 "/run/current-system/provenance"
                               read)))
    (define channels
      (sexp->system-provenance provenance))

    (check-forward-update validate-reconfigure
                          #:current-channels channels)))

(define (machine-check-building-for-appropriate-system machine)
  "Raise a '&message' error condition if MACHINE is configured to be built
locally and the 'system' field does not match the '%current-system' reported
by MACHINE."
  (let ((config (machine-configuration machine))
        (system (remote-system (machine-ssh-session machine))))
    (when (and (machine-ssh-configuration-build-locally? config)
               (not (string= system (machine-ssh-configuration-system config))))
      (raise (formatted-message (G_ "incorrect target system\
 ('~a' was given, while the system reports that it is '~a')~%")
                                (machine-ssh-configuration-system config)
                                system)))))

(define (check-deployment-sanity machine)
  "Raise a '&message' error condition if it is clear that deploying MACHINE's
'system' declaration would fail."
  (define assertions
    (append (machine-check-file-system-availability machine)
            (machine-check-initrd-modules machine)
            (list (machine-check-forward-update machine))))

  (define aggregate-exp
    ;; Gather all the expressions so that a single round-trip is enough to
    ;; evaluate all the ASSERTIONS remotely.
    #~(map (lambda (file)
             (false-if-exception (primitive-load file)))
           '#$(map (lambda (assertion)
                     (scheme-file "remote-assertion.scm"
                                  (remote-assertion-expression assertion)))
                   assertions)))

  ;; First check MACHINE's system type--an incorrect value for 'system' would
  ;; cause subsequent invocations of 'remote-eval' to fail.
  (machine-check-building-for-appropriate-system machine)

  (mlet %store-monad ((values (machine-remote-eval machine aggregate-exp)))
    (for-each (lambda (proc value)
                (proc value))
              (map remote-assertion-procedure assertions)
              values)
    (return #t)))

;;;
;;; System deployment.
;;;

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

(define (machine-boot-parameters machine)
  "Monadic procedure returning a list of 'boot-parameters' for the generations
of MACHINE's system profile, ordered from most recent to oldest."
  (define bootable-kernel-arguments
    (@@ (gnu system) bootable-kernel-arguments))

  (define remote-exp
    (with-extensions (list guile-gcrypt)
      (with-imported-modules `(((guix config) => ,(make-config.scm))
                               ,@(source-module-closure
                                  '((guix profiles))
                                  #:select? not-config?))
        #~(begin
            (use-modules (guix config)
                         (guix profiles)
                         (ice-9 textual-ports))

            (define %system-profile
              (string-append %state-directory "/profiles/system"))

            (define (read-file path)
              (call-with-input-file path
                (lambda (port)
                  (get-string-all port))))

            (map (lambda (generation)
                   (let* ((system-path (generation-file-name %system-profile
                                                             generation))
                          (boot-parameters-path (string-append system-path
                                                               "/parameters"))
                          (time (stat:mtime (lstat system-path))))
                     (list generation
                           system-path
                           time
                           (read-file boot-parameters-path))))
                 (reverse (generation-numbers %system-profile)))))))

  (mlet* %store-monad ((generations (machine-remote-eval machine remote-exp)))
    (return
     (map (lambda (generation)
            (match generation
              ((generation system-path time serialized-params)
               (let* ((params (call-with-input-string serialized-params
                                read-boot-parameters))
                      (root (boot-parameters-root-device params))
                      (label (boot-parameters-label params)))
                 (boot-parameters
                  (inherit params)
                  (label
                   (string-append label " (#"
                                  (number->string generation) ", "
                                  (let ((time (make-time time-utc 0 time)))
                                    (date->string (time-utc->date time)
                                                  "~Y-~m-~d ~H:~M"))
                                  ")"))
                  (kernel-arguments
                   (append (bootable-kernel-arguments system-path root)
                           (boot-parameters-kernel-arguments params))))))))
          generations))))

(define-syntax-rule (with-roll-back should-roll-back? mbody ...)
  "Catch exceptions that arise when binding MBODY, a monadic expression in
%STORE-MONAD, and collect their arguments in a &deploy-error condition, with
the 'should-roll-back' field set to SHOULD-ROLL-BACK?"
  (catch #t
    (lambda ()
      mbody ...)
    (lambda args
      (raise (condition (&deploy-error
                         (should-roll-back should-roll-back?)
                         (captured-args args)))))))

(define (deploy-managed-host machine)
  "Internal implementation of 'deploy-machine' for MACHINE instances with an
environment type of 'managed-host."
  (maybe-raise-unsupported-configuration-error machine)
  (when (machine-ssh-configuration-authorize?
         (machine-configuration machine))
    (unless (file-exists? %public-key-file)
      (raise (formatted-message (G_ "no signing key '~a'. \
have you run 'guix archive --generate-key?'")
                                %public-key-file)))
    (remote-authorize-signing-key (call-with-input-file %public-key-file
                                    (lambda (port)
                                      (string->canonical-sexp
                                       (get-string-all port))))
                                  (machine-ssh-session machine)
                                  (machine-become-command machine)))
  (mlet %store-monad ((_ (check-deployment-sanity machine))
                      (boot-parameters (machine-boot-parameters machine)))
    (let* ((os (machine-operating-system machine))
           (host (machine-ssh-configuration-host-name
                  (machine-configuration machine)))
           (eval (cut machine-remote-eval machine <>))
           (menu-entries (map boot-parameters->menu-entry boot-parameters))
           (bootloader-configuration (operating-system-bootloader os))
           (bootcfg (operating-system-bootcfg os menu-entries)))
      (define-syntax-rule (eval/error-handling condition handler ...)
        ;; Return a wrapper around EVAL such that HANDLER is evaluated if an
        ;; exception is raised.
        (lambda (exp)
          (lambda (store)
            (guard (condition ((inferior-exception? condition)
                               (values (begin handler ...) store)))
              (values (run-with-store store (eval exp))
                      store)))))

      (mbegin %store-monad
        (with-roll-back #f
          (switch-to-system (eval/error-handling c
                              (raise (formatted-message
                                      (G_ "\
failed to switch systems while deploying '~a':~%~{~s ~}")
                                      host
                                      (inferior-exception-arguments c))))
                            os))
        (with-roll-back #t
          (mbegin %store-monad
            (upgrade-shepherd-services (eval/error-handling c
                                         (warning (G_ "\
an error occurred while upgrading services on '~a':~%~{~s ~}~%")
                                                  host
                                                  (inferior-exception-arguments
                                                   c)))
                                       os)
            (install-bootloader (eval/error-handling c
                                  (raise (formatted-message
                                          (G_ "\
failed to install bootloader on '~a':~%~{~s ~}~%")
                                          host
                                          (inferior-exception-arguments c))))
                                bootloader-configuration bootcfg)))))))

;;;
;;; Roll-back.
;;;

(define (roll-back-managed-host machine)
  "Internal implementation of 'roll-back-machine' for MACHINE instances with
an environment type of 'managed-host."
  (define remote-exp
    (with-extensions (list guile-gcrypt)
      (with-imported-modules (source-module-closure '((guix config)
                                                      (guix profiles)))
        #~(begin
            (use-modules (guix config)
                         (guix profiles))

            (define %system-profile
              (string-append %state-directory "/profiles/system"))

            (define target-generation
              (relative-generation %system-profile -1))

            (if target-generation
                (switch-to-generation %system-profile target-generation)
                'error)))))

  (define roll-back-failure
    (condition (&message (message (G_ "could not roll-back machine")))))

  (mlet* %store-monad ((boot-parameters (machine-boot-parameters machine))
                       (_ -> (if (< (length boot-parameters) 2)
                                 (raise roll-back-failure)))
                       (entries -> (map boot-parameters->menu-entry
                                        (list (second boot-parameters))))
                       (locale -> (boot-parameters-locale
                                   (second boot-parameters)))
                       (crypto-dev -> (boot-parameters-store-crypto-devices
                                       (second boot-parameters)))
                       (store-dir -> (boot-parameters-store-directory-prefix
                                      (second boot-parameters)))
                       (old-entries -> (map boot-parameters->menu-entry
                                            (drop boot-parameters 2)))
                       (bootloader -> (operating-system-bootloader
                                       (machine-operating-system machine)))
                       (bootcfg (lower-object
                                 ((bootloader-configuration-file-generator
                                   (bootloader-configuration-bootloader
                                    bootloader))
                                  bootloader entries
                                  #:locale locale
                                  #:store-crypto-devices crypto-dev
                                  #:store-directory-prefix store-dir
                                  #:old-entries old-entries)))
                       (remote-result (machine-remote-eval machine remote-exp)))
    (when (eqv? 'error remote-result)
      (raise roll-back-failure))))

;;;
;;; Environment type.
;;;

(define managed-host-environment-type
  (environment-type
   (machine-remote-eval managed-host-remote-eval)
   (deploy-machine      deploy-managed-host)
   (roll-back-machine   roll-back-managed-host)
   (name                'managed-host-environment-type)
   (description         "Provisioning for machines that are accessible over SSH
and have a known host-name. This entails little more than maintaining an SSH
connection to the host.")))

(define (maybe-raise-unsupported-configuration-error machine)
  "Raise an error if MACHINE's configuration is not an instance of
<machine-ssh-configuration>."
  (let ((config (machine-configuration machine))
        (environment (environment-type-name (machine-environment machine))))
    (unless (and config (machine-ssh-configuration? config))
      (raise (formatted-message (G_ "unsupported machine configuration '~a'
for environment of type '~a'")
                                config
                                environment)))))

;; Local Variables:
;; eval: (put 'remote-let 'scheme-indent-function 1)
;; eval: (put 'with-roll-back 'scheme-indent-function 1)
;; eval: (put 'eval/error-handling 'scheme-indent-function 1)
;; End:

repo_name: maximed/guix

license: mit


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2013 Mark H Weaver <mhw@netris.org>
;;; Copyright © 2014 Eric Bavier <bavier@member.fsf.org>
;;; Copyright © 2016, 2017 Alex Kost <alezost@gmail.com>
;;; Copyright © 2016 Mathieu Lirzin <mthl@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 packages)
  #:use-module (guix packages)
  #:use-module (guix ui)
  #:use-module (guix utils)
  #:use-module (guix diagnostics)
  #:use-module (guix discovery)
  #:use-module (guix memoization)
  #:use-module ((guix build utils)
                #:select ((package-name->name+version
                           . hyphen-separated-name->name+version)
                          mkdir-p))
  #:use-module (guix profiles)
  #:use-module (guix describe)
  #:use-module (guix deprecation)
  #:use-module (ice-9 vlist)
  #:use-module (ice-9 match)
  #:use-module (ice-9 binary-ports)
  #:autoload   (system base compile) (compile)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-11)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module (srfi srfi-39)
  #:export (search-patch
            search-patches
            search-auxiliary-file
            %patch-path
            %auxiliary-files-path
            %package-module-path
            %default-package-module-path

            fold-packages
            fold-available-packages

            find-newest-available-packages
            find-packages-by-name
            find-package-locations
            find-best-packages-by-name

            specification->package
            specification->package+output
            specification->location
            specifications->manifest

            generate-package-cache))

;;; Commentary:
;;;
;;; General utilities for the software distribution---i.e., the modules under
;;; (gnu packages ...).
;;;
;;; Code:

;; By default, we store patches and auxiliary files
;; alongside Guile modules.  This is so that these extra files can be
;; found without requiring a special setup, such as a specific
;; installation directory and an extra environment variable.  One
;; advantage of this setup is that everything just works in an
;; auto-compilation setting.

(define %auxiliary-files-path
  (make-parameter
   (map (cut string-append <> "/gnu/packages/aux-files")
        %load-path)))

(define (search-auxiliary-file file-name)
  "Search the auxiliary FILE-NAME.  Return #f if not found."
  (search-path (%auxiliary-files-path) file-name))

(define (search-patch file-name)
  "Search the patch FILE-NAME.  Raise an error if not found."
  (or (search-path (%patch-path) file-name)
      (raise (formatted-message (G_ "~a: patch not found")
                                file-name))))

(define-syntax-rule (search-patches file-name ...)
  "Return the list of absolute file names corresponding to each
FILE-NAME found in %PATCH-PATH."
  (list (search-patch file-name) ...))

(define %distro-root-directory
  ;; Absolute file name of the module hierarchy.  Since (gnu packages …) might
  ;; live in a directory different from (guix), try to get the best match.
  (letrec-syntax ((dirname* (syntax-rules ()
                              ((_ file)
                               (dirname file))
                              ((_ file head tail ...)
                               (dirname (dirname* file tail ...)))))
                  (try      (syntax-rules ()
                              ((_ (file things ...) rest ...)
                               (match (search-path %load-path file)
                                 (#f
                                  (try rest ...))
                                 (absolute
                                  (dirname* absolute things ...))))
                              ((_)
                               #f))))
    (try ("gnu/packages/base.scm" gnu/ packages/)
         ("gnu/packages.scm"      gnu/)
         ("guix.scm"))))

(define %default-package-module-path
  ;; Default search path for package modules.
  `((,%distro-root-directory . "gnu/packages")))

(define (cache-is-authoritative?)
  "Return true if the pre-computed package cache is authoritative.  It is not
authoritative when entries have been added via GUIX_PACKAGE_PATH or '-L'
flags."
  (equal? (%package-module-path)
          (append %default-package-module-path
                  (package-path-entries))))

(define %package-module-path
  ;; Search path for package modules.  Each item must be either a directory
  ;; name or a pair whose car is a directory and whose cdr is a sub-directory
  ;; to narrow the search.
  (let*-values (((not-colon)
                 (char-set-complement (char-set #\:)))
                ((environment)
                 (string-tokenize (or (getenv "GUIX_PACKAGE_PATH") "")
                                  not-colon))
                ((channels-scm channels-go)
                 (package-path-entries)))
    ;; Automatically add channels and items from $GUIX_PACKAGE_PATH to Guile's
    ;; search path.  For historical reasons, $GUIX_PACKAGE_PATH goes to the
    ;; front; channels go to the back so that they don't override Guix' own
    ;; modules.
    (set! %load-path
      (append environment %load-path channels-scm))
    (set! %load-compiled-path
      (append environment %load-compiled-path channels-go))

    (make-parameter
     (append environment
             %default-package-module-path
             channels-scm))))

(define %patch-path
  ;; Define it after '%package-module-path' so that '%load-path' contains user
  ;; directories, allowing patches in $GUIX_PACKAGE_PATH to be found.
  (make-parameter
   (map (lambda (directory)
          (if (string=? directory %distro-root-directory)
              (string-append directory "/gnu/packages/patches")
              directory))
        %load-path)))

;; This procedure is used by Emacs-Guix up to 0.5.1.1, so keep it for now.
;; See <https://github.com/alezost/guix.el/issues/30>.
(define-deprecated find-newest-available-packages
  find-packages-by-name
  (mlambda ()
    "Return a vhash keyed by package names, and with
associated values of the form

  (newest-version newest-package ...)

where the preferred package is listed first."
    (fold-packages (lambda (p r)
                     (let ((name    (package-name p))
                           (version (package-version p)))
                       (match (vhash-assoc name r)
                         ((_ newest-so-far . pkgs)
                          (case (version-compare version newest-so-far)
                            ((>) (vhash-cons name `(,version ,p) r))
                            ((=) (vhash-cons name `(,version ,p ,@pkgs) r))
                            ((<) r)))
                         (#f (vhash-cons name `(,version ,p) r)))))
                   vlist-null)))

(define (fold-available-packages proc init)
  "Fold PROC over the list of available packages.  For each available package,
PROC is called along these lines:

  (PROC NAME VERSION RESULT
        #:outputs OUTPUTS
        #:location LOCATION
        …)

PROC can use #:allow-other-keys to ignore the bits it's not interested in.
When a package cache is available, this procedure does not actually load any
package module."
  (define cache
    (load-package-cache (current-profile)))

  (if (and cache (cache-is-authoritative?))
      (vhash-fold (lambda (name vector result)
                    (match vector
                      (#(name version module symbol outputs
                              supported? deprecated?
                              file line column)
                       (proc name version result
                             #:outputs outputs
                             #:location (and file
                                             (location file line column))
                             #:supported? supported?
                             #:deprecated? deprecated?))))
                  init
                  cache)
      (fold-packages (lambda (package result)
                       (proc (package-name package)
                             (package-version package)
                             result
                             #:outputs (package-outputs package)
                             #:location (package-location package)
                             #:supported?
                             (->bool (supported-package? package))
                             #:deprecated?
                             (->bool
                              (package-superseded package))))
                     init)))

(define* (fold-packages proc init
                        #:optional
                        (modules (all-modules (%package-module-path)
                                              #:warn
                                              warn-about-load-error))
                        #:key (select? (negate hidden-package?)))
  "Call (PROC PACKAGE RESULT) for each available package defined in one of
MODULES that matches SELECT?, using INIT as the initial value of RESULT.  It
is guaranteed to never traverse the same package twice."
  (fold-module-public-variables (lambda (object result)
                                  (if (and (package? object) (select? object))
                                      (proc object result)
                                      result))
                                init
                                modules))

(define %package-cache-file
  ;; Location of the package cache.
  "/lib/guix/package.cache")

(define load-package-cache
  (mlambda (profile)
    "Attempt to load the package cache.  On success return a vhash keyed by
package names.  Return #f on failure."
    (match profile
      (#f #f)
      (profile
       (catch 'system-error
         (lambda ()
           (define lst
             (load-compiled (string-append profile %package-cache-file)))
           (fold (lambda (item vhash)
                   (match item
                     (#(name version module symbol outputs
                             supported? deprecated?
                             file line column)
                      (vhash-cons name item vhash))))
                 vlist-null
                 lst))
         (lambda args
           (if (= ENOENT (system-error-errno args))
               #f
               (apply throw args))))))))

(define find-packages-by-name/direct              ;bypass the cache
  (let ((packages (delay
                    (fold-packages (lambda (p r)
                                     (vhash-cons (package-name p) p r))
                                   vlist-null)))
        (version>? (lambda (p1 p2)
                     (version>? (package-version p1) (package-version p2)))))
    (lambda* (name #:optional version)
      "Return the list of packages with the given NAME.  If VERSION is not #f,
then only return packages whose version is prefixed by VERSION, sorted in
decreasing version order."
      (let ((matching (sort (vhash-fold* cons '() name (force packages))
                            version>?)))
        (if version
            (filter (lambda (package)
                      (version-prefix? version (package-version package)))
                    matching)
            matching)))))

(define (cache-lookup cache name)
  "Lookup package NAME in CACHE.  Return a list sorted in increasing version
order."
  (define (package-version<? v1 v2)
    (version>? (vector-ref v2 1) (vector-ref v1 1)))

  (sort (vhash-fold* cons '() name cache)
        package-version<?))

(define* (find-packages-by-name name #:optional version)
  "Return the list of packages with the given NAME.  If VERSION is not #f,
then only return packages whose version is prefixed by VERSION, sorted in
decreasing version order."
  (define cache
    (load-package-cache (current-profile)))

  (if (and (cache-is-authoritative?) cache)
      (match (cache-lookup cache name)
        (#f #f)
        ((#(_ versions modules symbols _ _ _ _ _ _) ...)
         (fold (lambda (version* module symbol result)
                 (if (or (not version)
                         (version-prefix? version version*))
                     (cons (module-ref (resolve-interface module)
                                       symbol)
                           result)
                     result))
               '()
               versions modules symbols)))
      (find-packages-by-name/direct name version)))

(define* (find-package-locations name #:optional version)
  "Return a list of version/location pairs corresponding to each package
matching NAME and VERSION."
  (define cache
    (load-package-cache (current-profile)))

  (if (and cache (cache-is-authoritative?))
      (match (cache-lookup cache name)
        (#f '())
        ((#(name versions modules symbols outputs
                 supported? deprecated?
                 files lines columns) ...)
         (fold (lambda (version* file line column result)
                 (if (and file
                          (or (not version)
                              (version-prefix? version version*)))
                     (alist-cons version* (location file line column)
                                 result)
                     result))
               '()
               versions files lines columns)))
      (map (lambda (package)
             (cons (package-version package) (package-location package)))
           (find-packages-by-name/direct name version))))

(define (find-best-packages-by-name name version)
  "If version is #f, return the list of packages named NAME with the highest
version numbers; otherwise, return the list of packages named NAME and at
VERSION."
  (if version
      (find-packages-by-name name version)
      (match (find-packages-by-name name)
        (()
         '())
        ((matches ...)
         ;; Return the subset of MATCHES with the higher version number.
         (let ((highest (package-version (first matches))))
           (take-while (lambda (p)
                         (string=? (package-version p) highest))
                       matches))))))

;; Prevent Guile 3 from inlining this procedure so we can mock it in tests.
(set! find-best-packages-by-name find-best-packages-by-name)

(define (generate-package-cache directory)
  "Generate under DIRECTORY a cache of all the available packages.

The primary purpose of the cache is to speed up package lookup by name such
that we don't have to traverse and load all the package modules, thereby also
reducing the memory footprint."
  (define cache-file
    (string-append directory %package-cache-file))

  (define expand-cache
    (match-lambda*
      (((module symbol variable) (result . seen))
       (let ((package (variable-ref variable)))
         (if (or (vhash-assq package seen)
                 (hidden-package? package))
             (cons result seen)
             (cons (cons `#(,(package-name package)
                            ,(package-version package)
                            ,(module-name module)
                            ,symbol
                            ,(package-outputs package)
                            ,(->bool (supported-package? package))
                            ,(->bool (package-superseded package))
                            ,@(let ((loc (package-location package)))
                                (if loc
                                    `(,(location-file loc)
                                      ,(location-line loc)
                                      ,(location-column loc))
                                    '(#f #f #f))))
                         result)
                   (vhash-consq package #t seen)))))))

  (define entry-key
    (match-lambda
      ((module symbol variable)
       (let ((value (variable-ref variable)))
         (string-append (package-name value) (package-version value)
                        (object->string module)
                        (symbol->string symbol))))))

  (define (entry<? a b)
    (string<? (entry-key a) (entry-key b)))

  (define variables
    ;; First sort variables so that 'expand-cache' later dismisses
    ;; already-seen package objects in a deterministic fashion.
    (sort
     (fold-module-public-variables* (lambda (module symbol variable lst)
                                      (let ((value (false-if-exception
                                                    (variable-ref variable))))
                                        (if (package? value)
                                            (cons (list module symbol variable)
                                                  lst)
                                            lst)))
                                    '()
                                    (all-modules (%package-module-path)
                                                 #:warn
                                                 warn-about-load-error))
     entry<?))

  (define exp
    (first (fold expand-cache (cons '() vlist-null) variables)))

  (mkdir-p (dirname cache-file))
  (call-with-output-file cache-file
    (lambda (port)
      ;; Store the cache as a '.go' file.  This makes loading fast and reduces
      ;; heap usage since some of the static data is directly mmapped.
      (put-bytevector port
                      (compile `'(,@exp)
                               #:to 'bytecode
                               #:opts '(#:to-file? #t)))))
  cache-file)

(define %sigint-prompt
  ;; The prompt to jump to upon SIGINT.
  (make-prompt-tag "interruptible"))

(define (call-with-sigint-handler thunk handler)
  "Call THUNK and return its value.  Upon SIGINT, call HANDLER with the signal
number in the context of the continuation of the call to this function, and
return its return value."
  (call-with-prompt %sigint-prompt
                    (lambda ()
                      (sigaction SIGINT
                        (lambda (signum)
                          (sigaction SIGINT SIG_DFL)
                          (abort-to-prompt %sigint-prompt signum)))
                      (dynamic-wind
                        (const #t)
                        thunk
                        (cut sigaction SIGINT SIG_DFL)))
                    (lambda (k signum)
                      (handler signum))))

;;;
;;; Package specification.
;;;

(define* (%find-package spec name version)
  (match (find-best-packages-by-name name version)
    ((pkg . pkg*)
     (unless (null? pkg*)
       (warning (G_ "ambiguous package specification `~a'~%") spec)
       (warning (G_ "choosing ~a@~a from ~a~%")
                (package-name pkg) (package-version pkg)
                (location->string (package-location pkg))))
     (match (package-superseded pkg)
       ((? package? new)
        (info (G_ "package '~a' has been superseded by '~a'~%")
              (package-name pkg) (package-name new))
        new)
       (#f
        pkg)))
    (x
     (if version
         (leave (G_ "~A: package not found for version ~a~%") name version)
         (leave (G_ "~A: unknown package~%") name)))))

(define (specification->package spec)
  "Return a package matching SPEC.  SPEC may be a package name, or a package
name followed by an at-sign and a version number.  If the version number is not
present, return the preferred newest version."
  (let-values (((name version) (package-name->name+version spec)))
    (%find-package spec name version)))

(define (specification->location spec)
  "Return the location of the highest-numbered package matching SPEC, a
specification such as \"guile@2\" or \"emacs\"."
  (let-values (((name version) (package-name->name+version spec)))
    (match (find-package-locations name version)
      (()
       (if version
           (leave (G_ "~A: package not found for version ~a~%") name version)
           (leave (G_ "~A: unknown package~%") name)))
      (lst
       (let* ((highest   (match lst (((version . _) _ ...) version)))
              (locations (take-while (match-lambda
                                       ((version . location)
                                        (string=? version highest)))
                                     lst)))
         (match locations
           (((version . location) . rest)
            (unless (null? rest)
              (warning (G_ "ambiguous package specification `~a'~%") spec)
              (warning (G_ "choosing ~a@~a from ~a~%")
                       name version
                       (location->string location)))
            location)))))))

(define* (specification->package+output spec #:optional (output "out"))
  "Return the package and output specified by SPEC, or #f and #f; SPEC may
optionally contain a version number and an output name, as in these examples:

  guile
  guile@2.0.9
  guile:debug
  guile@2.0.9:debug

If SPEC does not specify a version number, return the preferred newest
version; if SPEC does not specify an output, return OUTPUT.

When OUTPUT is false and SPEC does not specify any output, return #f as the
output."
  (let-values (((name version sub-drv)
                (package-specification->name+version+output spec output)))
    (match (%find-package spec name version)
      (#f
       (values #f #f))
      (package
       (if (or (and (not output) (not sub-drv))
               (member sub-drv (package-outputs package)))
           (values package sub-drv)
           (leave (G_ "package `~a' lacks output `~a'~%")
                  (package-full-name package)
                  sub-drv))))))

(define (specifications->manifest specs)
  "Given SPECS, a list of specifications such as \"emacs@25.2\" or
\"guile:debug\", return a profile manifest."
  ;; This procedure exists mostly so users of 'guix package -m' don't have to
  ;; fiddle with multiple-value returns.
  (packages->manifest
   (map (compose list specification->package+output) specs)))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2015, 2016 Leo Famulari <leo@famulari.name>
;;; Copyright © 2020 Björn Höfling <bjoern.hoefling@bjoernhoefling.de>
;;;
;;; 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 packages abduco)
  #:use-module (guix build-system gnu)
  #:use-module (guix utils)
  #:use-module (guix download)
  #:use-module (guix licenses)
  #:use-module (guix packages))

(define-public abduco
  (package
   (name "abduco")
   (version "0.6")
   (source (origin
            (method url-fetch)
            (uri (string-append
                  "https://www.brain-dump.org/projects/abduco/abduco-"
                  version ".tar.gz"))
            (sha256
             (base32
              "1x1m58ckwsprljgmdy93mvgjyg9x3cqrzdf3mysp0mx97zhhj2f9"))))
   (build-system gnu-build-system)
   (arguments
    `(#:make-flags (list (string-append "CC=" ,(cc-for-target))
                         (string-append "PREFIX=" (assoc-ref %outputs "out")))
      #:phases (modify-phases %standard-phases
                 (delete 'configure)
                 (delete 'check)))) ; no test suite
   (synopsis "Session management in a clean and simple way")
   (description "abduco provides session management i.e. it allows programs to
be run independently from their controlling terminal.  That is, programs can
be detached---run in the background---and then later reattached.")
   (home-page "https://www.brain-dump.org/projects/abduco/")
   (license isc)))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2014 Marek Benc <merkur32@gmail.com>
;;; Copyright © 2016, 2018 Efraim Flashner <efraim@flashner.co.il>
;;; Copyright © 2017 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2017 Leo Famulari <leo@famulari.name>
;;; Copyright © 2018, 2021 Tobias Geerinckx-Rice <me@tobias.gr>
;;; Copyright © 2020 Oleg Pykhalov <go.wigust@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 packages abiword)
  #:use-module ((guix licenses) #:prefix license:)
  #:use-module (guix packages)
  #:use-module (guix download)
  #:use-module (guix build-system gnu)
  #:use-module (guix build-system glib-or-gtk)
  #:use-module (gnu packages)
  #:use-module (gnu packages autotools)
  #:use-module (gnu packages boost)
  #:use-module (gnu packages compression)
  #:use-module (gnu packages enchant)
  #:use-module (gnu packages fribidi)
  #:use-module (gnu packages fontutils)
  #:use-module (gnu packages glib)
  #:use-module (gnu packages gnome)
  #:use-module (gnu packages gtk)
  #:use-module (gnu packages image)
  #:use-module (gnu packages ots)
  #:use-module (gnu packages popt)
  #:use-module (gnu packages pkg-config)
  #:use-module (gnu packages readline)
  #:use-module (gnu packages wv)
  #:use-module (gnu packages xml))

(define-public abiword
  (package
    (name "abiword")
    (version "3.0.5")
    (source
      (origin
        (method url-fetch)
        (uri
          (string-append "https://www.abisource.com/downloads/abiword/" version
                         "/source/abiword-" version ".tar.gz"))
        (sha256
         (base32 "1d1179pnslijpjhz1q155fsc828rrlqf7lsn2inqsl3hk5z28mqj"))
        (patches
         (search-patches "abiword-explictly-cast-bools.patch"))))

    (build-system glib-or-gtk-build-system)
    (arguments                   ;; NOTE: rsvg is disabled, since Abiword
      `(#:configure-flags        ;; supports it directly, and its BS is broken.
        (list                    ;; wmf was removed from Guix for security.
          "--enable-clipart"     ;; TODO: The following plugins have unresolved
          "--enable-templates"   ;; dependencies: aiksaurus, grammar, wpg, gda,
          (string-append         ;; wordperfect, psion, mathview.
            "--enable-plugins="
              "applix " "babelfish " "bmp " "clarisworks " "collab " "command "
              "docbook " "eml " "epub " "freetranslation " "garble " "gdict "
              "gimp " "goffice " "google " "hancom " "hrtext " "iscii " "kword "
              "latex " "loadbindings " "mht " "mif " "mswrite " "opendocument "
              "openwriter " "openxml " "opml " "ots " "paint " "passepartout "
              "pdb " "pdf " "presentation " "s5 " "sdw " "t602 " "urldict "
              "wikipedia " "wml " "xslfo"))
        ;; tests fail with: Gtk-CRITICAL **: gtk_settings_get_for_screen:
        ;;                  assertion 'GDK_IS_SCREEN (screen)' failed
        ;;                  GLib-GObject-CRITICAL **: g_object_get_qdata:
        ;;                  assertion 'G_IS_OBJECT (object)' failed
        ;; Manually starting the X server before the test phase did not help
        ;; the tests to pass.
        #:tests? #f
        #:make-flags
        (list "gtk_update_icon_cache=true")))
    (inputs
      `(("boost" ,boost)
        ("enchant" ,enchant)
        ("fontconfig" ,fontconfig)
        ("fribidi" ,fribidi)
        ("glib" ,glib)
        ("goffice" ,goffice)
        ("gtk+" ,gtk+)
        ("libchamplain" ,libchamplain)
        ("libglade" ,libglade)
        ("libgsf" ,libgsf)
        ("libjpeg" ,libjpeg-turbo)
        ("libpng" ,libpng)
        ("librsvg" ,librsvg)
        ("libxml2" ,libxml2)
        ("libxslt" ,libxslt)
        ("ots" ,ots)
        ("popt" ,popt)
        ("readline" ,readline)
        ("telepathy" ,telepathy-glib)
        ("wv" ,wv)
        ("zlib" ,zlib)))
    (native-inputs
      `(("intltool" ,intltool)
        ("glib:bin" ,glib "bin")
        ("libtool" ,libtool)
        ("pkg-config" ,pkg-config)))
    (home-page "https://www.abisource.com/")
    (synopsis "Word processing program")

    ;; HACKERS: The comment below is here so that it shows up early in the
    ;; .pot file.

    ;; TRANSLATORS: Dear translator, We would like to inform you that package
    ;; descriptions may occasionally include Texinfo markup.  Texinfo markup
    ;; looks like "@code{rm -rf}", "@emph{important}", etc.  When translating,
    ;; please leave markup as is.
    (description "AbiWord is a word processing program.  It is rapidly
becoming a state of the art word processor, with lots of features useful for
your daily work, personal needs, or for just some good old typing fun.")
    (license license:gpl2+)))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2017 Nikita <nikita@n0.is>
;;; Copyright © 2017 Stefan Reichör <stefan@xsteve.at>
;;; Copyright © 2018, 2021 Tobias Geerinckx-Rice <me@tobias.gr>
;;; Copyright © 2019 Andrew Miloradovsky <andrew@interpretmath.pw>
;;; Copyright © 2020 Efraim Flashner <efraim@flashner.co.il>
;;;
;;; 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 packages accessibility)
  #:use-module ((guix licenses) #:prefix license:)
  #:use-module (guix utils)
  #:use-module (guix packages)
  #:use-module (guix download)
  #:use-module (guix git-download)
  #:use-module (guix build-system gnu)
  #:use-module (guix build-system glib-or-gtk)
  #:use-module (gnu packages)
  #:use-module (gnu packages lisp)
  #:use-module (gnu packages base)
  #:use-module (gnu packages ocaml)
  #:use-module (gnu packages pcre)
  #:use-module (gnu packages polkit)
  #:use-module (gnu packages ncurses)
  #:use-module (gnu packages music)
  #:use-module (gnu packages language)
  #:use-module (gnu packages icu4c)
  #:use-module (gnu packages speech)
  #:use-module (gnu packages linux)
  #:use-module (gnu packages documentation)
  #:use-module (gnu packages swig)
  #:use-module (gnu packages libusb)
  #:use-module (gnu packages java)
  #:use-module (gnu packages python)
  #:use-module (gnu packages python-xyz)
  #:use-module (gnu packages tcl)
  #:use-module (gnu packages xml)
  #:use-module (gnu packages gnome)
  #:use-module (gnu packages gstreamer)
  #:use-module (gnu packages gtk)
  #:use-module (gnu packages xorg)
  #:use-module (gnu packages gettext)
  #:use-module (gnu packages glib)
  #:use-module (gnu packages pkg-config)
  #:use-module (gnu packages libusb))

(define-public libbraille
  (package
    (name "libbraille")
    (version "0.19.0")
    (source
     (origin
       (method url-fetch)
       (uri
        (string-append "https://sourceforge.net/projects/" name "/files/" name "/"
                       name "-" version "/" name "-" version ".tar.gz"))
       (sha256
        (base32 "05g8r0ypazqn10i7k48iibs8bzc3scdfcnhcykab8j16lhzd27d0"))))
    (build-system glib-or-gtk-build-system)
    (outputs '("out" "bin"))
    (arguments
     `(#:tests? #f                      ; Tests require drivers
       #:configure-flags
       (list
        "--disable-static"
        "--enable-fake")))
    (native-inputs
     `(("latex2html" ,latex2html)
       ("pkg-config" ,pkg-config)
       ("python" ,python-wrapper)
       ("swig" ,swig)))
    (inputs
     `(("glib" ,glib)
       ("gtk+" ,gtk+-2)
       ("libusb" ,libusb-compat)))
    (synopsis "Portable Braille Library")
    (description "Libbraille is a library to easily access Braille displays and
terminals.")
    (home-page "https://libbraille.org")
    (license license:lgpl2.1+)))

(define-public brltty
  (package
    (name "brltty")
    (version "6.2")
    (source
     (origin
       (method url-fetch)
       (uri
        (string-append "https://brltty.app/archive/brltty-" version ".tar.gz"))
       (sha256
        (base32 "0m0cq3p1cwp52n81si621gij82w3mdqwgr39m6bs652pmk5na72l"))))
    (build-system glib-or-gtk-build-system)
    (arguments
     `(#:tests? #f                      ; No target
       #:configure-flags
       (list
        (string-append "--with-tcl-config="
                       (assoc-ref %build-inputs "tcl")
                       "/lib/tclConfig.sh")
        (string-append "--with-libbraille="
                       (assoc-ref %build-inputs "libbraille"))
        (string-append "--with-espeak_ng="
                       (assoc-ref %build-inputs "espeak-ng"))
        (string-append "--with-espeak="
                       (assoc-ref %build-inputs "espeak"))
        (string-append "--with-flite="
                       (assoc-ref %build-inputs "flite"))
        ;; Required for RUNPATH validation.
        (string-append "LDFLAGS=-Wl,-rpath="
                       (assoc-ref %outputs "out")
                       "/lib"))
       #:make-flags
       (list
        (string-append "JAVA_JAR_DIR="
                       (assoc-ref %outputs "out"))
        (string-append "JAVA_JNI_DIR="
                       (assoc-ref %outputs "out"))
        (string-append "OCAML_DESTDIR="
                       (assoc-ref %outputs "out")
                       "/lib")
        (string-append "PYTHON_PREFIX="
                       (assoc-ref %outputs "out"))
        "PYTHON_ROOT=/"
        (string-append "TCL_DIR="
                       (assoc-ref %outputs "out")
                       "/lib")
        "INSTALL_WRITABLE_DIRECTORY=no-thanks")
       #:phases
       (modify-phases %standard-phases
         (add-after 'unpack 'fix-errors
           (lambda* (#:key outputs #:allow-other-keys)
             (substitute* "configure"
               (("/sbin/ldconfig")
                (which "true")))
             ;; Make Python bindings use rpath.
             (substitute* "Bindings/Python/setup.py.in"
               (("extra_compile_args =")
                (string-append "extra_link_args = ['-Wl,-rpath="
                               (assoc-ref outputs "out")
                               "/lib'], "
                               "extra_compile_args = ")))
             #t)))))
    (native-inputs
     `(("clisp" ,clisp)
       ("cython" ,python-cython)
       ("doxygen" ,doxygen)
       ("gettext" ,gettext-minimal)
       ("java" ,icedtea "jdk")
       ;; ("linuxdoc" ,linuxdoc-tools)
       ("ocaml" ,ocaml)
       ("ocamlfind" ,ocaml-findlib)
       ("pkg-config" ,pkg-config)
       ("python" ,python-wrapper)
       ("tcl" ,tcl)))
    (inputs
     `(("alsa" ,alsa-lib)
       ("atspi2" ,at-spi2-core)
       ("bluez" ,bluez)
       ("dbus" ,dbus)
       ("espeak" ,espeak)
       ("espeak-ng" ,espeak-ng)
       ("expat" ,expat)
       ("festival" ,festival)
       ("flite" ,flite)
       ("glib" ,glib)
       ("gpm" ,gpm)
       ("iconv" ,libiconv)
       ("icu" ,icu4c)
       ("libbraille" ,libbraille)
       ("libpcre2" ,pcre2)
       ("linux-headers" ,linux-libre-headers)
       ("louis" ,liblouis)
       ("ncurses" ,ncurses)
       ("polkit" ,polkit)
       ("speech-dispatcher" ,speech-dispatcher)
       ("util-linux" ,util-linux)
       ("util-linux:lib" ,util-linux "lib")
       ("x11" ,libx11)
       ("xaw" ,libxaw)
       ("xaw3d" ,libxaw3d)
       ("xext" ,libxext)
       ("xfixes" ,libxfixes)
       ("xt" ,libxt)
       ("xtst" ,libxtst)))
    (synopsis "Braille TTY")
    (description "BRLTTY is a background process (daemon) which provides access
to the Linux/Unix console (when in text mode) for a blind person using a
refreshable braille display.  It drives the braille display, and provides
complete screen review functionality.  Some speech capability has also been
incorporated.")
    (home-page "https://brltty.app/")
    (license license:lgpl2.1+)))

(define-public florence
  (package
    (name "florence")
    (version "0.6.3")
    (source
     (origin
       (method url-fetch)
       (uri (string-append "mirror://sourceforge/florence/florence/" version
                           "/florence-" version ".tar.bz2"))
       (sha256
        (base32
         "07h9qm22krlwayhzvc391lr23vicw81s48g7rirvx1fj0zyr4aa2"))))
    (build-system glib-or-gtk-build-system)
    (arguments
     `(#:configure-flags (list "--with-xtst"
                               "--without-docs"
                               "--with-notification")))
    (inputs
     `(("libxml2" ,libxml2)
       ("libglade" ,libglade)
       ("librsvg" ,librsvg)
       ("gstreamer" ,gstreamer)
       ("cairo" ,cairo)
       ("gtk+" ,gtk+)
       ("libxtst" ,libxtst)
       ("libxcomposite" ,libxcomposite)
       ("libnotify" ,libnotify)))
    (native-inputs
     `(("gettext-minimal" ,gettext-minimal)
       ("intltool" ,intltool)
       ("pkg-config" ,pkg-config)))
    (home-page "http://florence.sourceforge.net/")
    (synopsis "Extensible, scalable virtual keyboard for X11")
    (description
     "Florence is an extensible scalable virtual keyboard for X11.
It is useful for people who can't use a real hardware keyboard (for
example for people with disabilities), but you must be able to use
a pointing device (as a mouse, a trackball, a touchscreen or opengazer).

Florence stays out of your way when you don't need it: it appears on the
screen only when you need it.  A timer-based auto-click input method is
available to help to click.")
    ;; The documentation is under FDL1.2, but we do not install the
    ;; documentation.
    (license license:gpl2+)))

(define-public footswitch
  (let ((commit "ca43d53fc2002520cc825d119702afc124303e73")
        (revision "2"))
    (package
      (name "footswitch")
      (version (git-version "0.1" revision commit))
      (source (origin
                (method git-fetch)
                (uri (git-reference
                      (url "https://github.com/rgerganov/footswitch")
                      (commit commit)))
                (file-name (git-file-name name version))
                (sha256
                 (base32
                  "14pyzc4ws1mj859xs9n4x83wzxxvd3bh5bdxzr6nv267xwx1mq68"))))
      (build-system gnu-build-system)
      (native-inputs
       `(("pkg-config" ,pkg-config)))
      (inputs
       `(("hidapi" ,hidapi)))
      (arguments
       `(#:tests? #f ; no tests
         #:make-flags (list (string-append "CC=" ,(cc-for-target)))
         #:phases (modify-phases %standard-phases
                    (delete 'configure)
                    ;; Install target in the Makefile does not work for Guix
                    (replace 'install
                      (lambda* (#:key outputs #:allow-other-keys)
                        (let ((bin (string-append (assoc-ref outputs "out")
                                                  "/bin")))
                          (install-file "footswitch" bin)
                          (install-file "scythe" bin)
                          #t))))))
      (home-page "https://github.com/rgerganov/footswitch")
      (synopsis "Command line utility for PCsensor foot switch")
      (description
       "Command line utility for programming foot switches sold by PCsensor.
It works for both single pedal devices and three pedal devices.  All supported
devices have vendorId:productId = 0c45:7403 or 0c45:7404.")
    (license license:expat))))

(define-public xmagnify
  (package
    (name "xmagnify")
    (version "0.1.0")
    (source (origin
              (method git-fetch)
              (uri (git-reference
                    (url "https://gitlab.com/amiloradovsky/magnify.git")
                    (commit version)))
              (file-name (git-file-name name version))
              (sha256
               (base32
                "1ngnp5f5zl3v35vhbdyjpymy6mwrs0476fm5nd7dzkba7n841jdh"))))
    (build-system gnu-build-system)
    (arguments
     `(#:tests? #f ; none included
       #:make-flags
       (list (string-append "CC=" ,(cc-for-target))
             (string-append "prefix=" (assoc-ref %outputs "out")))
       #:phases
       (modify-phases %standard-phases
         (delete 'configure))))
    (inputs
     `(("libX11" ,libx11)))
    (home-page "https://gitlab.com/amiloradovsky/magnify")
    (synopsis "Tiny screen magnifier for X11")
    (description
     "This program magnifies a screen region by an integer positive factor and
draws the result on a window.  It is useful as an accessibility tool, which
works with every X Window System based GUI (depends only on libX11); or as an
assistant for graphic designers, who need to select individual pixels.")
    ;; Licensed either under Expat or GPLv2+.
    (license (list license:expat license:gpl2+))))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
;;; Copyright © 2020 Björn Höfling <bjoern.hoefling@bjoernhoefling.de>
;;;
;;; 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 packages acct)
  #:use-module (guix licenses)
  #:use-module (guix packages)
  #:use-module (guix download)
  #:use-module (guix build-system gnu))

(define-public acct
  (package
    (name "acct")
    (version "6.6.4")
    (source
     (origin
      (method url-fetch)
      (uri (string-append "mirror://gnu/acct/acct-"
                          version ".tar.gz"))
      (sha256
       (base32
        "0gv6m8giazshvgpvwbng98chpas09myyfw1zr2y7hqxib0mvy5ac"))))
    (build-system gnu-build-system)
    (home-page "https://www.gnu.org/software/acct/")
    (synopsis "Standard login and process accounting utilities")
    (description
     "GNU acct provides a means for system administrators to determine
system usage patterns.  It provides information on, for example, connections,
programs executed, and system resources used.")
    (license gpl3+)))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2012 Nikita Karetnikov <nikita@karetnikov.org>
;;; Copyright © 2014, 2018 Mark H Weaver <mhw@netris.org>
;;; Copyright © 2014 Andreas Enge <andreas@enge.fr>
;;; Copyright © 2017 Efraim Flashner <efraim@flashner.co.il>
;;; Copyright © 2018 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2019 Marius Bakke <mbakke@fastmail.com>
;;; Copyright © 2020 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
;;; Copyright © 2021 Lars-Dominik Braun <ldb@leibniz-psychology.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 packages acl)
  #:use-module (guix licenses)
  #:use-module (gnu packages attr)
  #:use-module (gnu packages base)
  #:use-module (gnu packages check)
  #:use-module (gnu packages hurd)
  #:use-module (gnu packages gettext)
  #:use-module (gnu packages perl)
  #:use-module (guix packages)
  #:use-module (guix download)
  #:use-module (gnu packages)
  #:use-module (guix build-system gnu)
  #:use-module (guix build-system python))

(define-public acl
  (package
    (name "acl")
    (version "2.2.53")
    (source
     (origin
      (method url-fetch)
      (uri (string-append "mirror://savannah/acl/acl-"
                          version ".tar.gz"))
      (sha256
       (base32
        "1ir6my3w74s6nfbgbqgzj6w570sn0qjf3524zx8xh67lqrjrigh6"))))
    (build-system gnu-build-system)
    (arguments
     `(#:modules ((ice-9 ftw)
                  ,@%gnu-build-system-modules)
       #:configure-flags '("--disable-static")
       #:tests? ,(not (or (%current-target-system)
                          (hurd-target?)))
       #:phases
       (modify-phases %standard-phases
         ;; XXX After repacking the sources the timestamps are reset to the
         ;; epoch, which leads to a failure in gzipping the CHANGES file.
         (add-after 'unpack 'ensure-no-mtimes-pre-1980
           (lambda _
             (let ((early-1980 315619200)) ; 1980-01-02 UTC
               (ftw "." (lambda (file stat flag)
                          (unless (<= early-1980 (stat:mtime stat))
                            (utime file early-1980 early-1980))
                          #t))
               #t)))
         (add-after 'build 'patch-exec-bin-sh
           (lambda _
             (substitute* "test/run"
               (("/bin/sh") (which "sh")))
             #t))
         (add-before 'check 'patch-tests
           (lambda _
             ;; The coreutils do not have an ACL bit to remove from their
             ;; output, so the sed expression that removes the bit is disabled.
             (substitute* "test/sbits-restore.test"
                          (("\\| sed.*'") ""))
             ;; These tests require the existence of a user named "bin", but
             ;; this user does not exist within Guix's build environment.
             (substitute* "Makefile.in"
               ((".*test/misc\\.test.*") "")
               ((".*test/cp\\.test.*") "")
               ((".*test/setfacl-X\\.test.*") ""))
             #t)))))
    (inputs `(("attr" ,attr)))
    (native-inputs
     `(("gettext" ,gettext-minimal)
       ("perl" ,perl)))
    (home-page "https://savannah.nongnu.org/projects/acl")
    (synopsis
     "Library and tools for manipulating access control lists")
    (description
     "Library and tools for manipulating access control lists.")
    (license (list gpl2+ lgpl2.1+))))

(define-public python-pylibacl
  (package
    (name "python-pylibacl")
    (version "0.6.0")
    (source
      (origin
        (method url-fetch)
        (uri (pypi-uri "pylibacl" version))
        (sha256
          (base32
            "1zyrk2m20p5b6bdwxhrwib273i6i71zyr5hzssbxfqis5qra9848"))))
    (build-system python-build-system)
    (arguments
     `(#:phases
       (modify-phases %standard-phases
         (add-after 'unpack 'disable-tests
           (lambda* (#:key outputs inputs #:allow-other-keys)
             ;; These tests operate on real files, but our tempfs does not support
             ;; ACLs
             (substitute* "tests/test_acls.py"
               (("( *)def test_applyto(_extended(_mixed)?)?" match indent)
                (string-append indent "@pytest.mark.skip(reason=\"guix\")\n" match)))
             #t))
         (replace 'check
           (lambda* (#:key inputs outputs tests? #:allow-other-keys)
             (when tests?
               (add-installed-pythonpath inputs outputs)
               (invoke "pytest" "tests"))
               #t)))))
    (inputs `(("acl" ,acl)))
    (native-inputs `(("python-pytest" ,python-pytest)))
    (home-page "https://pylibacl.k1024.org/")
    (synopsis "POSIX.1e ACLs for python")
    (description "Python 3.4+ extension module that allows you to manipulate
the POSIX.1e Access Control Lists present in some OS/file-systems
combinations.")
    (license lgpl2.1+)))