code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2013, 2015, 2017 David Thompson <dthompson2@worcester.edu>
;;; Copyright © 2014 Mark H Weaver <mhw@netris.org>
;;; Copyright © 2015, 2017 Sou Bunnbu <iyzsong@member.fsf.org>
;;; Copyright © 2015 Alex Kost <alezost@gmail.com>
;;; Copyright © 2016, 2017 Efraim Flashner <efraim@flashner.co.il>
;;; Copyright © 2017, 2018, 2019 Rutger Helling <rhelling@mykolab.com>
;;; Copyright © 2018, 2019 Tobias Geerinckx-Rice <me@tobias.gr>
;;; Copyright © 2018, 2019, 2020 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2019 Kei Kebreau <kkebreau@posteo.net>
;;; Copyright © 2019, 2020 Nicolas Goaziou <mail@nicolasgoaziou.fr>
;;; Copyright © 2019 Marius Bakke <mbakke@fastmail.com>
;;; Copyright © 2019 Pierre Neidhardt <mail@ambrevar.xyz>
;;; Copyright © 2020 Timotej Lazar <timotej.lazar@araneo.si>
;;; 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 sdl)
  #:use-module (ice-9 match)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:use-module (gnu packages)
  #:use-module ((guix licenses) #:hide (freetype))
  #:use-module (guix packages)
  #:use-module (guix download)
  #:use-module (guix git-download)
  #:use-module (guix utils)
  #:use-module (guix build-system gnu)
  #:use-module (guix build-system trivial)
  #:use-module (gnu packages audio)
  #:use-module (gnu packages autotools)
  #:use-module (gnu packages fcitx)
  #:use-module (gnu packages fontutils)
  #:use-module (gnu packages freedesktop)
  #:use-module (gnu packages glib)
  #:use-module (gnu packages gtk)
  #:use-module (gnu packages guile)
  #:use-module (gnu packages ibus)
  #:use-module (gnu packages image)
  #:use-module (gnu packages linux)
  #:use-module (gnu packages mono)
  #:use-module (gnu packages mp3)
  #:use-module (gnu packages pkg-config)
  #:use-module (gnu packages pulseaudio)
  #:use-module (gnu packages gl)
  #:use-module (gnu packages xdisorg)
  #:use-module (gnu packages xiph)
  #:use-module (gnu packages xorg)
  #:export (sdl-union))

(define-public sdl
  (package
    (name "sdl")
    (version "1.2.15")
    (source (origin
             (method url-fetch)
             (uri
              (string-append "https://libsdl.org/release/SDL-"
                             version ".tar.gz"))
             (sha256
              (base32
               "005d993xcac8236fpvd1iawkz4wqjybkpn8dbwaliqz5jfkidlyn"))
             (patches (search-patches "sdl-libx11-1.6.patch"))))
    (build-system gnu-build-system)
    (arguments
     '(;; Explicitly link against shared libraries instead of dlopening them.
       ;; For X11, ALSA, and PulseAudio.
       ;; OpenGL library is still dlopened at runtime.
       #:configure-flags '("--disable-alsa-shared"
                           "--disable-pulseaudio-shared"
                           "--disable-x11-shared"
                           ;; Explicitly link with mesa.
                           ;; This add mesa to libsdl's RUNPATH, to make dlopen
                           ;; finding the libGL from mesa at runtime.
                           "LDFLAGS=-lGL")

       #:make-flags '("V=1")            ;build verbosely

       #:tests? #f)) ; no check target
    (propagated-inputs
     ;; SDL headers include X11 headers.
     `(("libx11" ,libx11)
       ("libcap" ,libcap) ; 'libSDL.la' contain `-lcap'.
       ;; TODO: Since building Mesa with Meson it is now necessary that Mesa is
       ;; a propogated input. We still need to figure out why, possibly due to a
       ;; change in pkg-config.
       ("mesa" ,mesa)))
    (native-inputs `(("pkg-config" ,pkg-config)))
    (inputs `(("libxrandr" ,libxrandr)
              ("glu" ,glu)
              ("alsa-lib" ,alsa-lib)
              ("pulseaudio" ,pulseaudio)))
    (outputs '("out" "debug"))
    (synopsis "Cross platform game development library")
    (description "Simple DirectMedia Layer is a cross-platform development
library designed to provide low level access to audio, keyboard, mouse,
joystick, and graphics hardware.")
    (home-page "https://libsdl.org/")
    (license lgpl2.1)))

(define-public sdl2
  (package (inherit sdl)
    (name "sdl2")
    (version "2.0.12")
    (source (origin
             (method url-fetch)
             (uri
              (string-append "https://libsdl.org/release/SDL2-"
                             version ".tar.gz"))
             (sha256
              (base32
               "0qy8wbqvfkb5ps8kxgaaf2zzpkjqbsw712hlp74znbn0jpv6i4il"))))
    (arguments
     (substitute-keyword-arguments (package-arguments sdl)
       ((#:configure-flags flags)
        `(append '("--disable-wayland-shared" "--enable-video-kmsdrm"
                   "--disable-kmsdrm-shared")
                 ,flags))
       ((#:make-flags flags ''())
        `(cons*
          ;; SDL dlopens libudev, so make sure it is in rpath. This overrides
          ;; the LDFLAG set in sdl’s configure-flags, which isn’t necessary
          ;; as sdl2 includes Mesa by default.
          (string-append "LDFLAGS=-Wl,-rpath,"
                         (assoc-ref %build-inputs "eudev") "/lib")
          ,flags))))
    (inputs
     ;; SDL2 needs to be built with ibus support otherwise some systems
     ;; experience a bug where input events are doubled.
     ;;
     ;; For more information, see: https://dev.solus-project.com/T1721
     (append `(("dbus" ,dbus)
               ("eudev" ,eudev) ; for discovering input devices
               ("fcitx" ,fcitx) ; helps with CJK input
               ("glib" ,glib)
               ("ibus" ,ibus)
               ("libxkbcommon" ,libxkbcommon)
               ("libxcursor" ,libxcursor) ; enables X11 cursor support
               ("wayland" ,wayland)
               ("wayland-protocols" ,wayland-protocols))
             (package-inputs sdl)))
    (license bsd-3)))

(define-public libmikmod
  (package
    (name "libmikmod")
    (version "3.3.11.1")
    (source (origin
             (method url-fetch)
             (uri (list
                   (string-append "mirror://sourceforge/mikmod/libmikmod/"
                                  version "/libmikmod-" version ".tar.gz")
                   ;; Older versions are sometimes moved to:
                   (string-append "mirror://sourceforge/mikmod/"
                                  "outdated_versions/libmikmod/"
                                  version "/libmikmod-" version ".tar.gz")))
             (sha256
              (base32
               "06bdnhb0l81srdzg6gn2v2ydhhaazza7rshrcj3q8dpqr3gn97dd"))))
    (build-system gnu-build-system)
    (arguments
     ;; By default, libmikmod tries to dlopen libasound etc., which won't work
     ;; unless the right libalsa happens to be in $LD_LIBRARY_PATH.  Pass
     ;; '--disable-dl' to avoid that.
     '(#:configure-flags '("--disable-dl")))
    (synopsis "Library for module sound formats")
    (description
     "MikMod is able to play a wide range of module formats, as well as
digital sound files.  It can take advantage of particular features of your
system, such as sound redirection over the network.")
    (license lgpl2.1)
    (home-page "http://mikmod.sourceforge.net/")))

(define-public sdl-gfx
  (package
    (name "sdl-gfx")
    (version "2.0.26")
    (source (origin
              (method url-fetch)
              (uri
               (string-append "http://www.ferzkopp.net/Software/SDL_gfx-2.0/SDL_gfx-"
                              version ".tar.gz"))
              (sha256
               (base32
                "0ijljhs0v99dj6y27hc10z6qchyp8gdp4199y6jzngy6dzxlzsvw"))))
    (build-system gnu-build-system)
    (outputs '("out" "debug"))
    (arguments
     `(,@(if (any (cute string-prefix? <> (or (%current-system)
                                              (%current-target-system)))
                  '("x86_64" "i686"))
        ;; mmx is supported only on Intel processors.
        '()
        '(#:configure-flags '("--disable-mmx")))))
    (propagated-inputs `(("sdl" ,sdl)))
    (synopsis "SDL graphics primitives library")
    (description "SDL_gfx provides graphics drawing primitives, rotozoom and
other supporting functions for SDL.")
    (home-page "http://www.ferzkopp.net/joomla/software-mainmenu-14/4-ferzkopps-linux-software/19-sdlgfx")
    (license zlib)))

(define-public sdl-image
  (package
    (name "sdl-image")
    (version "1.2.12")
    (source (origin
             (method url-fetch)
             (uri
              (string-append "https://www.libsdl.org/projects/SDL_image/release/SDL_image-"
                             version ".tar.gz"))
             (sha256
              (base32
               "16an9slbb8ci7d89wakkmyfvp7c0cval8xw4hkg0842nhhlp540b"))))
    (build-system gnu-build-system)
    (outputs '("out" "debug"))
    (arguments
     ;; Explicitly link against shared libraries instead of dlopening them.
     '(#:configure-flags '("--disable-jpg-shared"
                           "--disable-png-shared"
                           "--disable-tif-shared"
                           "--disable-webp-shared")))
    (native-inputs `(("pkg-config" ,pkg-config)))
    ;; libjpeg, libpng, and libtiff are propagated inputs because the
    ;; SDL_image headers include the headers of these libraries.  SDL is a
    ;; propagated input because the pkg-config file refers to SDL's pkg-config
    ;; file.
    (propagated-inputs `(("sdl" ,sdl)
                         ("libjpeg" ,libjpeg-turbo)
                         ("libpng" ,libpng)
                         ("libtiff" ,libtiff)
                         ("libwebp" ,libwebp)))
    (synopsis "SDL image loading library")
    (description "SDL_image is an image file loading library for SDL that
supports the following formats: BMP, GIF, JPEG, LBM, PCX, PNG, PNM, TGA, TIFF,
WEBP, XCF, XPM, and XV.")
    (home-page "https://www.libsdl.org/projects/SDL_image/")
    (license zlib)))

(define-public sdl-mixer
  (package
    (name "sdl-mixer")
    (version "1.2.12")
    (source (origin
              (method url-fetch)
              (uri
               (string-append "https://www.libsdl.org/projects/SDL_mixer/release/SDL_mixer-"
                              version ".tar.gz"))
              (sha256
               (base32
                "0alrhqgm40p4c92s26mimg9cm1y7rzr6m0p49687jxd9g6130i0n"))))
    (build-system gnu-build-system)
    (outputs '("out" "debug"))
    (arguments
     `(#:tests? #f ; No check target.
       #:configure-flags
       '("--enable-music-mp3-mad-gpl" ; Use libmad instead of smpeg.
         ;; Explicitly link against shared libraries instead of dlopening them.
         "--disable-music-flac-shared"
         "--disable-music-fluidsynth-shared"
         "--disable-music-mod-shared"
         "--disable-music-ogg-shared")
       #:phases
       (modify-phases %standard-phases
         (add-after 'unpack 'fix-fluidsynth
           (lambda* (#:key inputs #:allow-other-keys)
             (substitute* "configure"
              (("EXTRA_LDFLAGS -lfluidsynth")
               (string-append "EXTRA_LDFLAGS "
                              "-L"
                              (assoc-ref inputs "fluidsynth")
                              "/lib -lfluidsynth")))
             #t)))))
    (inputs
     `(("fluidsynth" ,fluidsynth)
       ("libflac" ,flac)
       ("libmad" ,libmad)
       ("libmikmod" ,libmikmod)
       ("libvorbis" ,libvorbis)))
    (propagated-inputs `(("sdl" ,sdl)))
    (synopsis "SDL multi-channel audio mixer library")
    (description "SDL_mixer is a multi-channel audio mixer library for SDL.
It supports any number of simultaneously playing channels of 16 bit stereo
audio, plus a single channel of music.  Supported formats include FLAC, MOD,
MIDI, Ogg Vorbis, and MP3.

This package supports two MIDI backends, selectable at runtime.  To use the
newer @code{fluidsynth} library, install a soundfont such as @code{fluid-3}
and specify it using the @code{SDL_SOUNDFONTS} environment variable.  For the
legacy @code{timidity} backend, install a patch set such as @code{freepats}
and set the path to the configuration file with @code{TIMIDITY_CFG}.")
    (home-page "https://www.libsdl.org/projects/SDL_mixer/")
    (license zlib)))

(define-public sdl-net
  (package
    (name "sdl-net")
    (version "1.2.8")
    (source (origin
              (method url-fetch)
              (uri
               (string-append "https://www.libsdl.org/projects/SDL_net/release/SDL_net-"
                              version ".tar.gz"))
              (sha256
               (base32
                "1d5c9xqlf4s1c01gzv6cxmg0r621pq9kfgxcg3197xw4p25pljjz"))))
    (build-system gnu-build-system)
    (propagated-inputs `(("sdl" ,sdl)))
    (native-inputs `(("pkg-config" ,pkg-config)))
    (outputs '("out" "debug"))
    (synopsis "SDL networking library")
    (description "SDL_net is a small, cross-platform networking library for
SDL.")
    (home-page "https://www.libsdl.org/projects/SDL_net/")
    (license zlib)))

(define-public sdl-pango
  (package
    (name "sdl-pango")
    (version "0.1.2")
    (source
     (origin
       (method url-fetch)
       (uri (string-append
             "mirror://sourceforge/sdlpango/SDL_Pango/" version "/"
             "SDL_Pango-" version  ".tar.gz"))
       (sha256
        (base32 "197baw1dsg0p4pljs5k0fshbyki00r4l49m1drlpqw6ggawx6xbz"))
       (patches (search-patches "sdl-pango-api_additions.patch"
                                "sdl-pango-blit_overflow.patch"
                                "sdl-pango-fillrect_crash.patch"
                                "sdl-pango-header-guard.patch"
                                "sdl-pango-matrix_declarations.patch"
                                "sdl-pango-sans-serif.patch"))))
    (build-system gnu-build-system)
    (arguments
     `(#:configure-flags (list "--disable-static")
       #:phases
       (modify-phases %standard-phases
         (add-after 'unpack 'autogen
           ;; Force reconfiguration because the included libtool
           ;; generates linking errors.
           (lambda _ (invoke "autoreconf" "-vif"))))))
    (native-inputs
     `(("autoconf" ,autoconf)
       ("automake" ,automake)
       ("libtool" ,libtool)
       ("pkg-config" ,pkg-config)))
    (inputs
     `(("fontconfig" ,fontconfig)
       ("freetype" ,freetype)
       ("glib" ,glib)
       ("harfbuzz" ,harfbuzz)
       ("pango" ,pango)
       ("sdl" ,sdl)))
    (home-page "http://sdlpango.sourceforge.net")
    (synopsis "Pango SDL binding")
    (description "This library is a wrapper around the Pango library.
It allows you to use TrueType fonts to render internationalized and
tagged text in SDL applications.")
    (license lgpl2.1)))

(define-public sdl-ttf
  (package
    (name "sdl-ttf")
    (version "2.0.11")
    (source (origin
             (method url-fetch)
             (uri
              (string-append "https://www.libsdl.org/projects/SDL_ttf/release/SDL_ttf-"
                             version ".tar.gz"))
             (sha256
              (base32
               "1dydxd4f5kb1288i5n5568kdk2q7f8mqjr7i7sd33nplxjaxhk3j"))))
    (build-system gnu-build-system)
    (propagated-inputs `(("sdl" ,sdl)))
    (inputs `(("freetype" ,freetype)
              ("mesa" ,mesa)))
    (native-inputs `(("pkg-config" ,pkg-config)))
    (outputs '("out" "debug"))
    (synopsis "SDL TrueType font library")
    (description "SDL_ttf is a TrueType font rendering library for SDL.")
    (home-page "https://www.libsdl.org/projects/SDL_ttf/")
    (license zlib)))

(define* (sdl-union #:optional (packages (list sdl sdl-gfx sdl-net sdl-ttf
                                               sdl-image sdl-mixer)))
  "Return 'sdl-union' package which is a union of PACKAGES.
If PACKAGES are not specified, all SDL packages are used."
  (package
    (name "sdl-union")
    (version (package-version sdl))
    (source #f)
    (build-system trivial-build-system)
    (arguments
     '(#:modules ((guix build union))
       #:builder (begin
                   (use-modules (ice-9 match)
                                (guix build union))
                   (match %build-inputs
                     (((names . directories) ...)
                      (union-build (assoc-ref %outputs "out")
                                   directories)
                      #t)))))
    (inputs (map (lambda (package)
                   (list (package-name package) package))
                 packages))
    (synopsis "Union of SDL libraries")
    (description
     "A union of SDL and its extension libraries.  A union is required because
sdl-config assumes that all of the headers and libraries are in the same
directory.")
    (home-page (package-home-page sdl))
    (license (package-license sdl))))

(define (propagated-inputs-with-sdl2 package)
  "Replace the \"sdl\" propagated input of PACKAGE with SDL2."
  (map (match-lambda
         (("sdl" _)
          `("sdl2" ,sdl2))
         (other other))
       (package-propagated-inputs package)))

(define-public sdl2-gfx
  (package (inherit sdl-gfx)
    (name "sdl2-gfx")
    (version "1.0.4")
    (source (origin
              (method url-fetch)
              (uri
               (string-append "https://www.ferzkopp.net/Software/SDL2_gfx/SDL2_gfx-"
                              version ".tar.gz"))
              (sha256
               (base32
                "0qk2ax7f7grlxb13ba0ll3zlm8780s7j8fmrhlpxzjgdvldf1q33"))))
    (propagated-inputs
     (propagated-inputs-with-sdl2 sdl-gfx))))

(define-public sdl2-image
  (package (inherit sdl-image)
    (name "sdl2-image")
    (version "2.0.5")
    (source
     (origin
       (method url-fetch)
       (uri
        (string-append "https://www.libsdl.org/projects/SDL_image/release/"
                       "SDL2_image-" version ".tar.gz"))
       (sha256
        (base32 "1l0864kas9cwpp2d32yxl81g98lx40dhbdp03dz7sbv84vhgdmdx"))))
    (propagated-inputs
     (propagated-inputs-with-sdl2 sdl-image))))

(define-public sdl2-mixer
  (package (inherit sdl-mixer)
    (name "sdl2-mixer")
    (version "2.0.4")
    (source
     (origin
       (method url-fetch)
       (uri
        (string-append "http://www.libsdl.org/projects/SDL_mixer/release/"
                       "SDL2_mixer-" version ".tar.gz"))
       (modules '((guix build utils)))
       (snippet '(begin
                   ;; Remove bundled libraries.
                   (delete-file-recursively "external")
                   #t))
       (sha256
        (base32 "0694vsz5bjkcdgfdra6x9fq8vpzrl8m6q96gh58df7065hw5mkxl"))))
    (arguments
      (substitute-keyword-arguments (package-arguments sdl-mixer)
         ((#:configure-flags flags)
          `(cons*
            "--disable-music-opus-shared"
            ;; These options were renamed in SDL2 mixer. Keeping the inherited
            ;; variants produces a harmless warning.
            "--disable-music-mod-modplug-shared"
            "--disable-music-midi-fluidsynth-shared"
            ,flags))))
    (inputs
     `(("opusfile" ,opusfile)
       ;; The default MOD library changed in SDL2 mixer.
       ("libmodplug" ,libmodplug)
       ,@(alist-delete "libmikmod" (package-inputs sdl-mixer))))
    (native-inputs
     `(("pkgconfig" ,pkg-config))) ; Needed to find the opus library.
    (propagated-inputs
     (propagated-inputs-with-sdl2 sdl-mixer))))

(define-public sdl2-net
  (package (inherit sdl-net)
    (name "sdl2-net")
    (version "2.0.1")
    (source
     (origin
       (method url-fetch)
       (uri
        (string-append "http://www.libsdl.org/projects/SDL_net/release/"
                       "SDL2_net-" version ".tar.gz"))
       (sha256
        (base32
         "08cxc1bicmyk89kiks7izw1rlx5ng5n6xpy8fy0zxni3b9z8mkhm"))))
    (propagated-inputs
     (propagated-inputs-with-sdl2 sdl-net))))

(define-public sdl2-ttf
  (package (inherit sdl-ttf)
    (name "sdl2-ttf")
    (version "2.0.15")
    (source (origin
             (method url-fetch)
             (uri
              (string-append "https://www.libsdl.org/projects/SDL_ttf/release/SDL2_ttf-"
                             version ".tar.gz"))
             (modules '((guix build utils)))
             (snippet (begin
                        ;; Remove bundled libraries.
                        '(delete-file-recursively "external")
                        #t))
             (sha256
              (base32
               "0cyd48dipc0m399qy8s03lci8b0bpiy8xlkvrm2ia7wcv0dfpv59"))))
    (propagated-inputs
     (propagated-inputs-with-sdl2 sdl-ttf))))

(define-public guile-sdl
  (package
    (name "guile-sdl")
    (version "0.5.2")
    (source (origin
              (method url-fetch)
              (uri
               (string-append "mirror://gnu/guile-sdl/guile-sdl-"
                              version ".tar.xz"))
              (sha256
               (base32
                "0cjgs012a9922hn6xqwj66w6qmfs3nycnm56hyykx5n3g5p7ag01"))))
    (build-system gnu-build-system)
    (native-inputs
     `(("pkg-config" ,pkg-config)
       ;; Required by test suite.
       ("xorg-server" ,xorg-server)
       ("libjpeg" ,libjpeg-turbo)))
    (inputs
     `(("guile" ,guile-2.2)
       ("sdl-union" ,(sdl-union))))
    (arguments
     '(#:configure-flags
       (list (string-append "--with-sdl-prefix="
                            (assoc-ref %build-inputs "sdl-union")))
       #:modules ((ice-9 popen)
                  (guix build utils)
                  (guix build gnu-build-system))

       #:parallel-build? #f ; parallel build fails

       #:phases
       (modify-phases %standard-phases
         (add-before 'configure 'fix-env-and-patch
           (lambda* (#:key inputs #:allow-other-keys)
             (setenv "GUILE_AUTO_COMPILE" "0")
             ;; SDL_image needs to dlopen libjpeg in the test suite.
             (setenv "LD_LIBRARY_PATH"
                     (string-append (assoc-ref inputs "libjpeg") "/lib"))

             ;; Change the site directory /site/X.Y like Guile expects.
             (substitute* "build-aux/guile-baux/re-prefixed-site-dirs"
               (("\"/site\"")
                (let ((effective
                       (read
                        (open-pipe* OPEN_READ
                                    "guile" "-c"
                                    "(write (effective-version))"))))
                  (string-append "\"/site/" effective "\""))))

             ;; Skip tests that rely on sound support, which is unavailable in
             ;; the build environment.
             (substitute* "test/Makefile.in"
               (("HAVE_MIXER = .*$")
                "HAVE_MIXER = 0\n"))
             #t))
         (add-before 'check 'start-xorg-server
           (lambda* (#:key inputs #:allow-other-keys)
             ;; The test suite requires a running X server.
             (system (format #f "~a/bin/Xvfb :1 &"
                             (assoc-ref inputs "xorg-server")))
             (setenv "DISPLAY" ":1")
             #t))
         (add-before 'check 'skip-cursor-test
           (lambda _
             ;; XXX: This test sometimes enters an endless loop, and sometimes
             ;; crashes with:
             ;;   guile: xcb_io.c:147: append_pending_request: Assertion `!xcb_xlib_unknown_seq_number' failed.
             ;; Skip it.
             (substitute* "test/cursor.scm"
               (("\\(SDL:init .*" all)
                (string-append "(exit 77)  ;" all "\n")))
             #t)))))
    (synopsis "Guile interface for SDL (Simple DirectMedia Layer)")
    (description "Guile-SDL is a set of bindings to the Simple DirectMedia
Layer (SDL).  With them, Guile programmers can have easy access to graphics,
sound and device input (keyboards, joysticks, mice, etc.).")
    (home-page "https://www.gnu.org/software/guile-sdl/")
    (license gpl3+)))

(define-public guile-sdl2
  (package
    (name "guile-sdl2")
    (version "0.6.0")
    (source (origin
              (method url-fetch)
              (uri (string-append "https://files.dthompson.us/guile-sdl2/"
                                  "guile-sdl2-" version ".tar.gz"))
              (sha256
               (base32
                "06vrknn4iz0ag932rb4almyhi9cvdkn081shvsi0h4skd6ry8bdl"))))
    (build-system gnu-build-system)
    (arguments
     '(#:make-flags '("GUILE_AUTO_COMPILE=0")))
    (native-inputs
     `(("guile" ,guile-2.2)
       ("pkg-config" ,pkg-config)))
    (inputs
     `(("sdl2" ,sdl2)
       ("sdl2-image" ,sdl2-image)
       ("sdl2-mixer" ,sdl2-mixer)
       ("sdl2-ttf" ,sdl2-ttf)))
    (synopsis "Guile bindings for SDL2")
    (home-page "https://dthompson.us/projects/guile-sdl2.html")
    (description
     "Guile-SDL2 provides Guile Scheme bindings for the SDL2 C shared library.
The bindings are written in pure Scheme using Guile's foreign function
interface.")
    (license lgpl3+)))

(define-public guile3.0-sdl2
  (package/inherit guile-sdl2
    (name "guile3.0-sdl2")
    (native-inputs
     `(("guile" ,guile-3.0)
       ("pkg-config" ,pkg-config)))))

(define-public sdl2-cs
  (let ((commit "1a3556441e1394eb0b5d46aeb514b8d1090b93f8"))
    (package
      (name "sdl2-cs")
      (version (git-version "B1" "1" commit))
      (source (origin
                (method git-fetch)
                (uri (git-reference
                      (url "https://github.com/flibitijibibo/SDL2-CS")
                      (commit commit)))
                (file-name (git-file-name name version))
                (sha256
                 (base32
                  "007mzkqr9nmvfrvvhs2r6cm36lzgsww24kwshsz9c4fd97f9qk58"))))
      (build-system gnu-build-system)
      (arguments
       '(#:tests? #f  ; No tests.
         #:phases
         (modify-phases %standard-phases
           (delete 'configure)
           (replace 'build
             (lambda _
               (invoke "make" "release")))
           (replace 'install
             (lambda* (#:key outputs #:allow-other-keys)
               (let ((out (assoc-ref outputs "out")))
                 (install-file "bin/Release/SDL2-CS.dll" (string-append out "/lib"))
                 #t))))))
      (native-inputs
       `(("mono" ,mono)))
      (inputs
       `(("sdl2" ,sdl2)
         ("sdl2-image" ,sdl2-image)
         ("sdl2-mixer" ,sdl2-mixer)
         ("sdl2-ttf" ,sdl2-ttf)))
      (home-page "https://dthompson.us/projects/guile-sdl2.html")
      (synopsis "C# wrapper for SDL2")
      (description
       "SDL2-CS provides C# bindings for the SDL2 C shared library.
The C# wrapper was written to be used for FNA's platform support.  However, this
is written in a way that can be used for any general C# application.")
      (license zlib))))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2014 Mark H Weaver <mhw@netris.org>
;;; Copyright © 2015, 2016 Eric Bavier <bavier@member.fsf.org>
;;; Copyright © 2017 Thomas Danckaert <post@thomasdanckaert.be>
;;; Copyright © 2017 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2018, 2020, 2021 Tobias Geerinckx-Rice <me@tobias.gr>
;;; Copyright © 2018 Adam Massmann <massmannak@gmail.com>
;;; Copyright © 2020 Hartmut Goebel <h.goebel@crazy-compilers.com>
;;; Copyright © 2021 Vinicius Monego <monego@posteo.net>
;;;
;;; 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 search)
  #:use-module ((guix licenses)
                #:select (gpl2 gpl2+ gpl3+ agpl3+ lgpl2.1+ bsd-3 x11 perl-license))
  #:use-module (guix packages)
  #:use-module (guix download)
  #:use-module (guix git-download)
  #:use-module (guix utils)
  #:use-module (guix build-system gnu)
  #:use-module (guix build-system perl)
  #:use-module (guix build-system python)
  #:use-module (gnu packages)
  #:use-module (gnu packages compression)
  #:use-module (gnu packages check)
  #:use-module (gnu packages databases)
  #:use-module (gnu packages freedesktop)
  #:use-module (gnu packages less)
  #:use-module (gnu packages linux)
  #:use-module (gnu packages pcre)
  #:use-module (gnu packages perl)
  #:use-module (gnu packages pdf)
  #:use-module (gnu packages python)
  #:use-module (gnu packages python-crypto)
  #:use-module (gnu packages python-web)
  #:use-module (gnu packages python-xyz)
  #:use-module (gnu packages sphinx)
  #:use-module (gnu packages time)
  #:use-module (gnu packages web)
  #:use-module (gnu packages xdisorg)
  #:use-module (gnu packages xml))

(define-public xapian
  (package
    (name "xapian")
    (version "1.4.18")
    ;; Note: When updating Xapian, remember to update xapian-bindings below.
    (source (origin
              (method url-fetch)
              (uri (string-append "https://oligarchy.co.uk/xapian/" version
                                  "/xapian-core-" version ".tar.xz"))
              (sha256
               (base32 "0xsb4ihf3p767f0zx9p4janwni6r9sg5j6lry0002i8hmnsdnv8r"))))
    (build-system gnu-build-system)
    (inputs `(("zlib" ,zlib)
              ("util-linux" ,util-linux "lib")))
    (arguments
     `(#:phases
       (modify-phases %standard-phases
         (replace 'check
           ;; As of Xapian 1.3.3, the TCP server implementation uses
           ;; getaddrinfo(). This does not work in the build environment,
           ;; so exclude those tests. See HACKING for the list of targets.
           (lambda _
             (invoke "make"
                     "check-inmemory"
                     "check-remoteprog"
                     ;"check-remotetcp"
                     "check-multi"
                     "check-glass"
                     "check-chert"))))))
    (synopsis "Search Engine Library")
    (description
     "Xapian is a highly adaptable toolkit which allows developers to easily
add advanced indexing and search facilities to their own applications.  It
supports the Probabilistic Information Retrieval model and also supports a
rich set of boolean query operators.")
    (home-page "https://xapian.org/")
    (license (list gpl2+ bsd-3 x11))))

(define-public python-xapian-bindings
  (package (inherit xapian)
    (name "python-xapian-bindings")
    (version (package-version xapian))
    (source (origin
              (method url-fetch)
              (uri (string-append "https://oligarchy.co.uk/xapian/" version
                                  "/xapian-bindings-" version ".tar.xz"))
              (sha256
               (base32
                "13ziql8027glgihgvnbsa75vkcn82g83mbihj60zf0njj170clpy"))))
    (build-system gnu-build-system)
    (arguments
     `(#:configure-flags '("--with-python3")
       #:make-flags
       (list (string-append "pkgpylibdir="
                            (assoc-ref %outputs "out")
                            "/lib/python" ,(version-major+minor
                                            (package-version python))
                            "/site-packages/xapian"))))
    (native-inputs
     `(("python-sphinx" ,python-sphinx))) ;for documentation
    (inputs
     `(("python" ,python)
       ("xapian" ,xapian)
       ("zlib" ,zlib)))
    (synopsis "Python bindings for the Xapian search engine library")
    (license gpl2+)))

(define-public perl-search-xapian
  (package
    (name "perl-search-xapian")
    (version "1.2.25.4")
    (source
     (origin
       (method url-fetch)
       (uri (string-append "mirror://cpan/authors/id/O/OL/OLLY/"
                           "Search-Xapian-" version ".tar.gz"))
       (sha256
        (base32 "1pbl8pbgmbs3i8yik4p63g4pd9bhn0dp3d7l667dkvw0kccl66c7"))))
    (build-system perl-build-system)
    (native-inputs
     `(("perl-devel-leak" ,perl-devel-leak)))
    (inputs
     `(("xapian" ,xapian)))
    (home-page "https://metacpan.org/release/Search-Xapian")
    (synopsis "Perl XS frontend to the Xapian C++ search library")
    (description
     "Search::Xapian wraps most methods of most Xapian classes.  The missing
classes and methods should be added in the future.  It also provides a
simplified, more 'perlish' interface to some common operations.")
    (license perl-license)))

(define-public libtocc
  (package
    (name "libtocc")
    (version "1.0.1")
    (source
     (origin
       (method url-fetch)
       (uri (string-append "https://github.com/aidin36/tocc/releases/download/"
                           "v" version "/tocc-" version ".tar.gz"))
       (sha256
        (base32
         "1kd2jd74m8ksc8s7hh0haz0q0c3n0mr39bbky262kk4l58f1g068"))))
    (build-system gnu-build-system)
    (native-inputs `(("catch" ,catch-framework)))
    (inputs `(("unqlite" ,unqlite)))
    (arguments
     `(#:phases (modify-phases %standard-phases
                  (add-before 'configure 'chdir-source
                    (lambda _
                      (chdir "libtocc/src")
                      #t))
                  (replace 'check
                    (lambda _
                      (with-directory-excursion "../tests"
                        (invoke "./configure"
                                (string-append "CONFIG_SHELL="
                                               (which "sh"))
                                (string-append "SHELL="
                                               (which "sh"))
                                "CPPFLAGS=-I../src"
                                (string-append
                                 "LDFLAGS=-L../src/.libs "
                                 "-Wl,-rpath=../src/.libs"))
                        (invoke "make")
                        (invoke "./libtocctests")))))))
    (home-page "https://t-o-c-c.com/")
    (synopsis "Tool for Obsessive Compulsive Classifiers")
    (description
     "libtocc is the engine of the Tocc project, a tag-based file management
system.  The goal of Tocc is to provide a better system for classifying files
that is more flexible than classic file systems that are based on a tree of
files and directories.")
    (license gpl3+)))

(define-public tocc
  (package
    (name "tocc")
    (version (package-version libtocc))
    (source (package-source libtocc))
    (build-system gnu-build-system)
    (inputs
     `(("libtocc" ,libtocc)
       ("unqlite" ,unqlite)))
    (arguments
     `(#:tests? #f                      ;No tests
       #:phases (modify-phases %standard-phases
                  (add-after
                   'unpack 'chdir-source
                   (lambda _ (chdir "cli/src"))))))
    (home-page "https://t-o-c-c.com/")
    (synopsis "Command-line interface to libtocc")
    (description
     "Tocc is a tag-based file management system.  This package contains the
command line tool for interacting with libtocc.")
    (license gpl3+)))

(define-public searx
  (package
    (name "searx")
    (version "1.0.0")
    (source
     (origin
       (method git-fetch)
       (uri (git-reference
             (url "https://github.com/searx/searx")
             (commit version)))
       (file-name (git-file-name name version))
       (sha256
        (base32 "0ghkx8g8jnh8yd46p4mlbjn2zm12nx27v7qflr4c8xhlgi0px0mh"))))
    (build-system python-build-system)
    (arguments
     `(#:tests? #f ;what tests do is make online requests to each engine
       #:phases
       (modify-phases %standard-phases
         (add-after 'unpack 'relax-requirements
           (lambda _
             ;; These packages are outdated in Guix at the time of packaging.
             ;; When they are updated, remove corresponding substitutions.
             ;; Tests can run after build with 'searx-checker' tool in /bin.
             (substitute* "requirements.txt"
               (("flask-babel==2.0.0") "flask-babel>=1.0.0")
               (("jinja2==2.11.3") "jinja2>=2.11.2")
               (("lxml==4.6.3") "lxml>=4.4.2")
               (("pygments==2.8.0") "pygments>=2.7.3")
               (("requests\\[socks\\]==2.25.1") "requests>=2.25")
               (("==") ">=")))))))
    (propagated-inputs
     `(("python-babel" ,python-babel)
       ("python-certifi" ,python-certifi)
       ("python-dateutil" ,python-dateutil)
       ("python-flask" ,python-flask)
       ("python-flask-babel" ,python-flask-babel)
       ("python-idna" ,python-idna)
       ("python-jinja2" ,python-jinja2)
       ("python-langdetect" ,python-langdetect)
       ("python-lxml" ,python-lxml)
       ("python-pygments" ,python-pygments)
       ("python-pyyaml" ,python-pyyaml)
       ("python-requests" ,python-requests)))
    (home-page "https://searx.github.io/searx/")
    (synopsis "Privacy-respecting metasearch engine")
    (description "Searx is a privacy-respecting, hackable metasearch engine.")
    (license agpl3+)))

(define-public bool
  (package
    (name "bool")
    (version "0.2.2")
    (source
     (origin
       (method url-fetch)
       (uri (string-append "mirror://gnu/bool/bool-"
                           version ".tar.xz"))
       (sha256
        (base32
         "1frdmgrmb509fxbdpsxxw3lvvwv7xm1pavqrqgm4jg698iix6xfw"))))
    (build-system gnu-build-system)
    (home-page "https://www.gnu.org/software/bool/")
    (synopsis "Finding text and HTML files that match boolean expressions")
    (description
     "GNU Bool is a utility to perform text searches on files using Boolean
expressions.  For example, a search for \"hello AND world\" would return a
file containing the phrase \"Hello, world!\".  It supports both AND and OR
statements, as well as the NEAR statement to search for the occurrence of
words in close proximity to each other.  It handles context gracefully,
accounting for new lines and paragraph changes.  It also has robust support
for parsing HTML files.")
    (license gpl3+)))

(define-public hyperestraier
  (package
    (name "hyperestraier")
    (version "1.4.13")
    (source
      (origin
        (method url-fetch)
        (uri (string-append "http://fallabs.com/" name "/"
                            name "-" version ".tar.gz"))
        (sha256
         (base32
          "1qk3pxgzyrpcz5qfyd5xs2hw9q1cbb7j5zd4kp1diq501wcj2vs9"))))
    (inputs
     `(("qdbm" ,qdbm)
       ("zlib" ,zlib)))
    (build-system gnu-build-system)
    (arguments
     `(#:configure-flags (list (string-append "LDFLAGS=-Wl,-rpath="
                                              (assoc-ref %outputs "out")
                                              "/lib"))))
    (home-page "https://fallabs.com/hyperestraier")
    (synopsis "Full-text search system")
    (description "Hyper Estraier can be used to integrate full-text
search into applications, using either the provided command line and CGI
interfaces, or a C API.")
    (license lgpl2.1+)))

(define-public mlocate
  (package
    (name "mlocate")
    (version "0.26")
    (source (origin
              (method url-fetch)
              (uri (string-append "http://releases.pagure.org/mlocate/"
                                  "mlocate-" version ".tar.xz"))
              (sha256
               (base32
                "0gi6y52gkakhhlnzy0p6izc36nqhyfx5830qirhvk3qrzrwxyqrh"))))
    (build-system gnu-build-system)
    (home-page "https://pagure.io/mlocate")
    (synopsis "Locate files on the file system")
    (description
     "mlocate is a locate/updatedb implementation.  The @code{m} stands for
\"merging\": @code{updatedb} reuses the existing database to avoid rereading
most of the file system, which makes it faster and does not trash the system
caches as much.  The locate(1) utility is intended to be completely compatible
with slocate, and attempts to be compatible to GNU locate when it does not
conflict with slocate compatibility.")
    (license gpl2)))

(define-public swish-e
  (package
    (name "swish-e")
    (version "2.4.7")
    (source (origin
              (method url-fetch)
              (uri (list (string-append
                          "https://web.archive.org/web/20160730145202/"
                          "http://swish-e.org/distribution/"
                          "swish-e-" version ".tar.gz")
                         (string-append "http://http.debian.net/debian/pool/"
                                        "main/s/swish-e/swish-e_" version
                                        ".orig.tar.gz")))
              (file-name (string-append name "-" version ".tar.gz"))
              (sha256
               (base32
                "0qkrk7z25yp9hynj21vxkyn7yi8gcagcfxnass5cgczcz0gm9pax"))
              (patches (search-patches "swish-e-search.patch"
                                       "swish-e-format-security.patch"))))
    (build-system gnu-build-system)
    ;; Several other packages and perl modules may be installed alongside
    ;; swish-e to extend its features at runtime, but are not required for
    ;; building: xpdf, catdoc, MP3::Tag, Spreadsheet::ParseExcel,
    ;; HTML::Entities.
    (inputs
     `(("perl" ,perl)
       ("perl-uri" ,perl-uri)
       ("perl-html-parser" ,perl-html-parser)
       ("perl-html-tagset" ,perl-html-tagset)
       ("perl-mime-types" ,perl-mime-types)))
    (arguments
     `(;; XXX: This fails to build with zlib (API mismatch) and tests fail
       ;; with libxml2, so disable both.
       #:configure-flags (list (string-append "--without-zlib")
                               (string-append "--without-libxml2"))
       #:phases (modify-phases %standard-phases
                  (add-after 'install 'wrap-programs
                    (lambda* (#:key inputs outputs #:allow-other-keys)
                      (let* ((out (assoc-ref outputs "out")))
                        (for-each
                         (lambda (program)
                           (wrap-program program
                             `("PERL5LIB" ":" prefix
                               ,(map (lambda (i)
                                       (string-append (assoc-ref inputs i)
                                                      "/lib/perl5/site_perl"))
                                     ;; These perl modules have no propagated
                                     ;; inputs, so no further analysis needed.
                                     '("perl-uri"
                                       "perl-html-parser"
                                       "perl-html-tagset"
                                       "perl-mime-types")))))
                         (list (string-append out "/lib/swish-e/swishspider")
                               (string-append out "/bin/swish-filter-test")))
                        #t))))))
    (home-page (string-append "https://web.archive.org/web/20160730145202/"
                              "http://swish-e.org"))
    (synopsis "Web indexing system")
    (description
     "Swish-e is Simple Web Indexing System for Humans - Enhanced.  Swish-e
can quickly and easily index directories of files or remote web sites and
search the generated indexes.")
    (license gpl2+)))                   ;with exception

(define-public xapers
  (package
    (name "xapers")
    (version "0.8.2")
    (source
     (origin
       (method url-fetch)
       (uri (string-append
             "https://finestructure.net/xapers/releases/xapers-"
             version ".tar.gz"))
       (sha256
        (base32
         "0ykz6hn3qj46w3c99d6q0pi5ncq2894simcl7vapv047zm3cylmd"))))
    (build-system python-build-system)
    (propagated-inputs
     `(("poppler" ,poppler)
       ("python-urwid" ,python-urwid)
       ("xclip" ,xclip)
       ("xdg-utils" ,xdg-utils)))
    (inputs
     `(("python-latexcodec" ,python-latexcodec)
       ("python-pybtex" ,python-pybtex)
       ("python-pycurl" ,python-pycurl)
       ("python-pyyaml" ,python-pyyaml)
       ("python-six" ,python-six)
       ("python-xapian-bindings" ,python-xapian-bindings)))
    (arguments
     `(#:modules ((ice-9 rdelim)
                  (guix build python-build-system)
                  (guix build utils))
       #:phases
       (modify-phases %standard-phases
         (add-after 'install 'install-doc
           (lambda* (#:key inputs outputs #:allow-other-keys)
             (define (purge-term-support input output)
               (let loop ((line (read-line input)))
                 (if (string-prefix? "if [[ \"$term\"" line)
                     (begin (display "eval \"$cmd\"\n" output)
                            #t)
                     (begin (display (string-append line "\n") output)
                            (loop (read-line input))))))
             (let* ((out (assoc-ref outputs "out"))
                    (bin (string-append out "/bin"))
                    (adder-out (string-append bin "/xapers-adder"))
                    (man1 (string-append out "/share/man/man1")))
               (install-file "man/man1/xapers.1"  man1)
               (install-file "man/man1/xapers-adder.1" man1)
               ;; below is equivalent to setting --no-term option
               ;; permanently on; this is desirable to avoid imposing
               ;; an x-terminal installation on the user but breaks
               ;; some potential xapers-adder uses like auto browser
               ;; pdf handler, but user could instead still use
               ;; e.g. "xterm -e xapers-adder %F" for same use.
               ;; alternatively we could propagate xterm as an input
               ;; and replace 'x-terminal-emulator' with 'xterm'
               (call-with-input-file "bin/xapers-adder"
                 (lambda (input)
                   (call-with-output-file adder-out
                     (lambda (output)
                       (purge-term-support input output)))))
               (chmod adder-out #o555)))))))
    (home-page "https://finestructure.net/xapers/")
    (synopsis "Personal document indexing system")
    (description
     "Xapers is a personal document indexing system,
geared towards academic journal articles build on the Xapian search engine.
Think of it as your own personal document search engine, or a local cache of
online libraries.  It provides fast search of document text and
bibliographic data and simple document and bibtex retrieval.")
    (license gpl3+)))

(define-public ugrep
  (package
    (name "ugrep")
    (version "3.1.12")
    (source (origin
              (method git-fetch)
              (uri (git-reference
                    (url "https://github.com/Genivia/ugrep")
                    (commit (string-append "v" version))))
              (sha256
               (base32 "06y61sf2ywjaix4nss11wwkxipj8cc9ccx6bsmdm31h8d8wd2s0j"))
              (file-name (git-file-name name version))
              (modules '((guix build utils)))
              (snippet
               '(begin
                  (delete-file-recursively "bin") ; pre-built executables
                  (for-each delete-file (find-files "tests" "^archive\\..*"))
                  (for-each delete-file (find-files "tests" "^.*\\.pdf$"))
                  (for-each delete-file (find-files "tests" "^.*\\.class$"))
                  #t))))
    (build-system gnu-build-system)
    (inputs
     `(("bzip2" ,bzip2)
       ("less" ,less)
       ("lz4" ,lz4)
       ("lzip" ,lzip)  ;; lzma
       ("pcre2" ,pcre2)
       ("zlib" ,zlib)))
    (arguments
     `(#:tests? #f                  ; no way to rebuild the binary input files
       #:test-target "test"
       #:phases
       (modify-phases %standard-phases
         (add-before 'check 'check-setup
           (lambda _
             ;; Unpatch shebangs in tests.
             (substitute* '("tests/Hello.bat"
                            "tests/Hello.sh")
               (("#!/gnu/store/.*/bin/sh") "#!/bin/sh")))))))
    (home-page "https://github.com/Genivia/ugrep/")
    (synopsis "Faster grep with an interactive query UI")
    (description "Ugrep is a ultra fast searcher of file systems, text
and binary files, source code, archives, compressed files, documents, and
more.

While still being compatible with the standard GNU/BSD grep command-line
options, ugrep supports fuzzy search as well as structured and (adjustable)
colored output, piped through \"less\" for pagination.  An interactive query
UI allows refinement and has a built-in help (press F1).  Ugrep implements
multi-threaded and other techniques to speed up search, pattern-matching and
decompression.  Many pre-defined regexps ease searching e.g. C typdefs or XML
attributes.  Results can be output in several structured or self-defined
formats.")
    (license bsd-3)))

;;; search.scm ends here

repo_name: maximed/guix

license: mit


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2014 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2016 Efraim Flashner <efraim@flashner.co.il>
;;; Copyright © 2016 Mike Gerwitz <mtg@gnu.org>
;;; Copyright © 2016 Marius Bakke <mbakke@fastmail.com>
;;; Copyright © 2017 Thomas Danckaert <post@thomasdanckaert.be>
;;; Copyright © 2017–2021 Tobias Geerinckx-Rice <me@tobias.gr>
;;; Copyright © 2017, 2019 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2018, 2019 Chris Marusich <cmmarusich@gmail.com>
;;; Copyright © 2018 Arun Isaac <arunisaac@systemreboot.net>
;;; Copyright © 2020 Raphaël Mélotte <raphael.melotte@mind.be>
;;; Copyright © 2021 Antero Mejr <antero@kodmin.com>
;;; Copyright © 2021 Sergey Trofimov <sarg@sarg.org.ru>
;;;
;;; 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 security-token)
  #:use-module (gnu packages)
  #:use-module ((guix licenses) #:prefix license:)
  #:use-module (guix packages)
  #:use-module (guix download)
  #:use-module (guix gexp)
  #:use-module (guix git-download)
  #:use-module (guix build-system cargo)
  #:use-module (guix build-system cmake)
  #:use-module (guix build-system gnu)
  #:use-module (guix build-system glib-or-gtk)
  #:use-module (guix build-system python)
  #:use-module (gnu packages autotools)
  #:use-module (gnu packages base)
  #:use-module (gnu packages curl)
  #:use-module (gnu packages check)
  #:use-module (gnu packages crates-io)
  #:use-module (gnu packages docbook)
  #:use-module (gnu packages documentation)
  #:use-module (gnu packages dns)
  #:use-module (gnu packages gettext)
  #:use-module (gnu packages graphviz)
  #:use-module (gnu packages gnupg)
  #:use-module (gnu packages gtk)
  #:use-module (gnu packages libusb)
  #:use-module (gnu packages linux)
  #:use-module (gnu packages man)
  #:use-module (gnu packages networking)
  #:use-module (gnu packages cyrus-sasl)
  #:use-module (gnu packages popt)
  #:use-module (gnu packages readline)
  #:use-module (gnu packages qt)
  #:use-module (gnu packages tls)
  #:use-module (gnu packages tex)
  #:use-module (gnu packages perl)
  #:use-module (gnu packages pkg-config)
  #:use-module (gnu packages python)
  #:use-module (gnu packages python-crypto)
  #:use-module (gnu packages python-xyz)
  #:use-module (gnu packages swig)
  #:use-module (gnu packages web)
  #:use-module (gnu packages xml))

(define-public ccid
  (package
    (name "ccid")
    (version "1.4.34")
    (source (origin
              (method url-fetch)
              (uri (string-append "https://ccid.apdu.fr/files/ccid-"
                                  version ".tar.bz2"))
              (sha256
               (base32
                "02mlbpnsvy6jgwpz0jk5lh27y3cn2bsyz9xini7898m9b5dn9xz6"))))
    (build-system gnu-build-system)
    (arguments
     `(#:configure-flags (list (string-append "--enable-usbdropdir=" %output
                                              "/pcsc/drivers"))
       #:phases
       (modify-phases %standard-phases
         (add-after 'unpack 'patch-Makefile
           (lambda _
             (substitute* "src/Makefile.in"
               (("/bin/echo") (which "echo")))
             #t)))))
    (native-inputs
     `(("perl" ,perl)
       ("pkg-config" ,pkg-config)))
    (inputs
     `(("libusb" ,libusb)
       ("pcsc-lite" ,pcsc-lite)))
    (home-page "https://ccid.apdu.fr/")
    (synopsis "PC/SC driver for USB smart card devices")
    (description
     "This package provides a PC/SC IFD handler implementation for devices
compliant with the CCID and ICCD protocols.  It supports a wide range of
readers and is needed to communicate with such devices through the
@command{pcscd} resource manager.")
    (license license:lgpl2.1+)))

(define-public eid-mw
  (package
    (name "eid-mw")
    (version "5.0.14")
    (source
     (origin
       (method git-fetch)
       (uri (git-reference
             (url "https://github.com/Fedict/eid-mw")
             (commit (string-append "v" version))))
       (file-name (git-file-name name version))
       (sha256
        (base32 "1hyxsbxjjn9hh5p7jlcfb5yplf3n8dg49dfgi8fjp95phis3gbd4"))))
    (build-system glib-or-gtk-build-system)
    (native-inputs
     `(("autoconf" ,autoconf)
       ("autoconf-archive" ,autoconf-archive)
       ("automake" ,automake)
       ("gettext" ,gettext-minimal)
       ("libtool" ,libtool)
       ("libassuan" ,libassuan)
       ("pkg-config" ,pkg-config)
       ("perl" ,perl)))
    (inputs
     `(("curl" ,curl)
       ("openssl" ,openssl)
       ("gtk+" ,gtk+)
       ("pcsc-lite" ,pcsc-lite)
       ("p11-kit" ,p11-kit)
       ("libproxy" ,libproxy)
       ("libxml2" ,libxml2)
       ("cyrus-sasl" ,cyrus-sasl)))
    (arguments
     `(#:configure-flags
       (list "--disable-static")
       #:phases
       (modify-phases %standard-phases
         (replace 'bootstrap
           (lambda _
             ;; configure.ac relies on ‘git --describe’ to get the version.
             ;; Patch it to just return the real version number directly.
             (substitute* "scripts/build-aux/genver.sh"
               (("/bin/sh") (which "sh"))
               (("^(GITDESC=).*" _ match) (string-append match ,version "\n")))
             (invoke "sh" "./bootstrap.sh")))
         (add-after 'unpack 'make-reproducible
           (lambda _
             (substitute* "scripts/mac/create-vers.sh"
               (("NOW=.*")
                "NOW=1970-01-01\n"))
             #t))
         ;; Remove failing test that was removed upstream after version 5.0.8.
         ;; See: https://github.com/Fedict/eid-mw/commit/3d1187b1b61118b9ae97607903d3d2fc0bad7518
         (add-before 'check 'remove-failing-test
           (lambda _
             (substitute* "tests/unit/Makefile.am"
               (("sign_state ordering cardcom_common")
                "sign_state ordering #cardcom_common"))
             #t))
         )))
    (synopsis "Belgian eID Middleware")
    (description "The Belgian eID Middleware is required to authenticate with
online services using the Belgian electronic identity card.")
    (home-page "https://github.com/Fedict/eid-mw")
    (license license:lgpl3)))

(define-public libyubikey
  (package
    (name "libyubikey")
    (version "1.13")
    (source (origin
              (method url-fetch)
              (uri (string-append
                    "https://developers.yubico.com/yubico-c/Releases/"
                    name "-" version ".tar.gz"))
              (sha256
               (base32
                "009l3k2zyn06dbrlja2d4p2vfnzjhlcqxi88v02mlrnb17mx1v84"))))
    (build-system gnu-build-system)
    (synopsis "Development kit for the YubiKey authentication device")
    (description
     "This package contains a C library and command-line tools that make up
the low-level development kit for the Yubico YubiKey authentication device.")
    (home-page "https://developers.yubico.com/yubico-c/")
    (license license:bsd-2)))

(define-public softhsm
  (package
    (name "softhsm")
    (version "2.6.1")
    (source (origin
              (method url-fetch)
              (uri (string-append
                    "https://dist.opendnssec.org/source/"
                    "softhsm-" version ".tar.gz"))
              (sha256
               (base32
                "1wkmyi6n3z2pak1cj5yk6v6bv9w0m24skycya48iikab0mrr8931"))))
    (build-system gnu-build-system)
    (arguments
     '(#:configure-flags '("--disable-gost"))) ; TODO Missing the OpenSSL
                                               ; engine for GOST
    (inputs
     `(("openssl" ,openssl)))
    (native-inputs
     `(("pkg-config" ,pkg-config)
       ("cppunit" ,cppunit)))
    (synopsis "Software implementation of a generic cryptographic device")
    (description
     "SoftHSM 2 is a software implementation of a generic cryptographic device
with a PKCS #11 Cryptographic Token Interface.")
    (home-page "https://www.opendnssec.org/softhsm/")
    (license license:bsd-2)))

(define-public pcsc-lite
  (package
    (name "pcsc-lite")
    (version "1.9.0")
    (source (origin
              (method url-fetch)
              (uri (string-append "https://pcsclite.apdu.fr/files/"
                                  "pcsc-lite-" version ".tar.bz2"))
              (sha256
               (base32
                "1y9f9zipnrmgiw0mxrvcgky8vfrcmg6zh40gbln5a93i2c1x8j01"))))
    (build-system gnu-build-system)
    (arguments
     `(#:configure-flags '("--enable-usbdropdir=/var/lib/pcsc/drivers"
                           "--disable-libsystemd")))
    (native-inputs
     `(("perl" ,perl)                   ; for pod2man
       ("pkg-config" ,pkg-config)))
    (inputs
     `(("libudev" ,eudev)))
    (home-page "https://pcsclite.apdu.fr/")
    (synopsis "Middleware to access a smart card using PC/SC")
    (description
     "pcsc-lite provides an interface to communicate with smartcards and
readers using the SCard API.  pcsc-lite is used to connect to the PC/SC daemon
from a client application and provide access to the desired reader.")
    (license (list license:bsd-3                ; pcsc-lite
                   license:isc                  ; src/strlcat.c src/strlcpy.c
                   license:gpl3+))))            ; src/spy/*

(define-public ykclient
  (package
    (name "ykclient")
    (version "2.15")
    (source (origin
              (method url-fetch)
              (uri (string-append
                    "https://developers.yubico.com/yubico-c-client/Releases/"
                    name "-" version ".tar.gz"))
              (sha256
               (base32
                "05jhx9waj3pl120ddnwap1v3bjrnbfhvf3lxs2xmhpcmwzpwsqgl"))))
    (build-system gnu-build-system)

    ;; There's just one test, and it requires network access to access
    ;; yubico.com, so skip it.
    (arguments '(#:tests? #f))

    (native-inputs `(("pkg-config" ,pkg-config)
                     ("help2man" ,help2man)))
    (inputs `(("curl" ,curl)))
    (synopsis "C library to validate one-time-password YubiKeys")
    (description
     "YubiKey C Client Library (libykclient) is a C library used to validate a
one-time-password (OTP) YubiKey against Yubico’s servers.  See the Yubico
website for more information about Yubico and the YubiKey.")
    (home-page "https://developers.yubico.com/yubico-c-client/")
    (license license:bsd-2)))

(define-public opensc
  (package
    (name "opensc")
    (version "0.21.0")
    (source (origin
              (method url-fetch)
              (uri (string-append
                    "https://github.com/OpenSC/OpenSC/releases/download/"
                    version "/opensc-" version ".tar.gz"))
              (sha256
               (base32
                "0pijycjwpll9zn83dazgsh8n9ywq0z1ragjsd1sqv3abrcfvpyrb"))))
    (build-system gnu-build-system)
    (arguments
     `(#:phases
       (modify-phases %standard-phases
         ;; By setting an absolute path here, we arrange for OpenSC to
         ;; successfully dlopen libpcsclite.so.1 by default.  The user can
         ;; still override this if they want to, by specifying a custom OpenSC
         ;; configuration file at runtime.
         (add-after 'unpack 'set-default-libpcsclite.so.1-path
           (lambda* (#:key inputs #:allow-other-keys)
             (let ((libpcsclite (string-append (assoc-ref inputs "pcsc-lite")
                                               "/lib/libpcsclite.so.1")))
               (substitute* "configure"
                 (("DEFAULT_PCSC_PROVIDER=\"libpcsclite\\.so\\.1\"")
                  (string-append
                   "DEFAULT_PCSC_PROVIDER=\"" libpcsclite "\"")))
               #t))))))
    (inputs
     `(("readline" ,readline)
       ("openssl" ,openssl)
       ("pcsc-lite" ,pcsc-lite)
       ("ccid" ,ccid)))
    (native-inputs
     `(("libxslt" ,libxslt)
       ("docbook-xsl" ,docbook-xsl)
       ("pkg-config" ,pkg-config)))
    (home-page "https://github.com/OpenSC/OpenSC/wiki")
    (synopsis "Tools and libraries related to smart cards")
    (description
     "OpenSC is a set of software tools and libraries to work with smart
cards, with the focus on smart cards with cryptographic capabilities.  OpenSC
facilitate the use of smart cards in security applications such as
authentication, encryption and digital signatures.  OpenSC implements the PKCS
#15 standard and the PKCS #11 API.")
    (license license:lgpl2.1+)))

(define-public yubico-piv-tool
  (package
    (name "yubico-piv-tool")
    (version "1.6.1")
    (source (origin
              (method url-fetch)
              (uri (string-append
                    "https://developers.yubico.com/yubico-piv-tool/Releases/"
                    name "-" version ".tar.gz"))
              (sha256
               (base32
                "10xgdc51xvszkxmsvqnbjs8ixxz7rfnfahh3wn8glllynmszbhwi"))))
    (build-system gnu-build-system)
    (inputs
     `(("gengetopt" ,gengetopt)
       ("perl" ,perl)
       ("pcsc-lite" ,pcsc-lite)
       ("openssl" ,openssl)))
    (native-inputs
     `(("doxygen" ,doxygen)
       ("graphviz" ,graphviz)
       ("help2man" ,help2man)
       ("check" ,check)
       ("texlive-bin" ,texlive-bin)
       ("pkg-config" ,pkg-config)))
    (home-page "https://developers.yubico.com/yubico-piv-tool/")
    (synopsis "Interact with the PIV application on a YubiKey")
    (description
     "The Yubico PIV tool is used for interacting with the Privilege and
Identification Card (PIV) application on a YubiKey.  With it you may generate
keys on the device, import keys and certificates, create certificate requests,
and other operations.  It includes a library and a command-line tool.")
    ;; The file ykcs11/pkcs11.h also declares an additional, very short free
    ;; license for that one file.  Please see it for details.  The vast
    ;; majority of files are licensed under bsd-2.
    (license license:bsd-2)))

(define-public yubikey-personalization
  (package
    (name "yubikey-personalization")
    (version "1.20.0")
    (source (origin
              (method url-fetch)
              (uri (string-append
                    "https://developers.yubico.com/" name
                    "/Releases/ykpers-" version ".tar.gz"))
              (sha256
               (base32
                "14wvlwqnwj0gllkpvfqiy8ns938bwvjsz8x1hmymmx32m074vj0f"))
              (modules '((guix build utils)))
              (snippet
               ;; Fix build with GCC 10, remove for versions > 1.20.0.
               '(begin
                  (substitute* "ykpers-args.h"
                    (("^const char")
                     "extern const char"))))))
    (build-system gnu-build-system)
    (arguments
     '(#:configure-flags (list (string-append "--with-udevrulesdir="
                                              (assoc-ref %outputs "out")
                                              "/lib/udev/rules.d"))))
    (inputs
     `(("json-c" ,json-c-0.13)
       ("libusb" ,libusb)
       ;; The library "libyubikey" is also known as "yubico-c".
       ("libyubikey" ,libyubikey)))
    (native-inputs
     `(("pkg-config" ,pkg-config)
       ("eudev" ,eudev)))
    (home-page "https://developers.yubico.com/yubikey-personalization/")
    (synopsis "Library and tools to personalize YubiKeys")
    (description
     "The YubiKey Personalization package contains a C library and command
line tools for personalizing YubiKeys.  You can use these to set an AES key,
retrieve a YubiKey's serial number, and so forth.")
    (license license:bsd-2)))

(define-public python-pyscard
  (package
    (name "python-pyscard")
    (version "1.9.9")
    (source (origin
              (method url-fetch)
              ;; The maintainer publishes releases on various sites, but
              ;; SourceForge is apparently the only one with a signed release.
              (uri (string-append
                    "mirror://sourceforge/pyscard/pyscard/pyscard%20"
                    version "/pyscard-" version ".tar.gz"))
              (sha256
               (base32
                "082cjkbxadaz2jb4rbhr0mkrirzlqyqhcf3r823qb0q1k50ybgg6"))))
    (build-system python-build-system)
    (arguments
     `(#:phases
       (modify-phases %standard-phases
         ;; Tell pyscard where to find the PCSC include directory.
         (add-after 'unpack 'patch-platform-include-dirs
           (lambda* (#:key inputs #:allow-other-keys)
             (let ((pcsc-include-dir (string-append
                                      (assoc-ref inputs "pcsc-lite")
                                      "/include/PCSC")))
               (substitute* "setup.py"
                 (("platform_include_dirs = \\[.*?\\]")
                  (string-append
                   "platform_include_dirs = ['" pcsc-include-dir "']")))
               #t)))
         ;; pyscard wants to dlopen libpcsclite, so tell it where it is.
         (add-after 'unpack 'patch-dlopen
           (lambda* (#:key inputs #:allow-other-keys)
             (substitute* "smartcard/scard/winscarddll.c"
               (("lib = \"libpcsclite\\.so\\.1\";")
                (simple-format #f
                               "lib = \"~a\";"
                               (string-append (assoc-ref inputs "pcsc-lite")
                                              "/lib/libpcsclite.so.1"))))
             #t)))))
    (inputs
     `(("pcsc-lite" ,pcsc-lite)))
    (native-inputs
     `(("swig" ,swig)))
    (home-page "https://github.com/LudovicRousseau/pyscard")
    (synopsis "Smart card library for Python")
    (description
     "The pyscard smart card library is a framework for building smart card
aware applications in Python.  The smart card module is built on top of the
PCSC API Python wrapper module.")
    (license license:lgpl2.1+)))

(define-public python2-pyscard
  (package-with-python2 python-pyscard))

(define-public libu2f-host
  (package
    (name "libu2f-host")
    (version "1.1.10")
    (source (origin
              (method url-fetch)
              (uri
               (string-append
                "https://developers.yubico.com"
                "/libu2f-host/Releases/libu2f-host-" version ".tar.xz"))
              (sha256
               (base32
                "0vrivl1dwql6nfi48z6dy56fwy2z13d7abgahgrs2mcmqng7hra2"))))
    (build-system gnu-build-system)
    (arguments
     `(#:configure-flags
       (list "--enable-gtk-doc"
             (string-append "--with-udevrulesdir="
                            (assoc-ref %outputs "out")
                            "/lib/udev/rules.d"))
       #:phases
       (modify-phases %standard-phases
         (add-after 'unpack 'patch-docbook-xml
           (lambda* (#:key inputs #:allow-other-keys)
             ;; Avoid a network connection attempt during the build.
             (substitute* "gtk-doc/u2f-host-docs.xml"
               (("http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd")
                (string-append (assoc-ref inputs "docbook-xml")
                               "/xml/dtd/docbook/docbookx.dtd")))
             #t)))))
    (inputs
     `(("json-c" ,json-c-0.13)
       ("hidapi" ,hidapi)))
    (native-inputs
     `(("help2man" ,help2man)
       ("gengetopt" ,gengetopt)
       ("pkg-config" ,pkg-config)
       ("gtk-doc" ,gtk-doc)
       ("docbook-xml" ,docbook-xml-4.3)
       ("eudev" ,eudev)))
    (home-page "https://developers.yubico.com/libu2f-host/")
    ;; TRANSLATORS: The U2F protocol has a "server side" and a "host side".
    (synopsis "U2F host-side C library and tool")
    (description
     "Libu2f-host provides a C library and command-line tool that implements
the host-side of the Universal 2nd Factor (U2F) protocol.  There are APIs to
talk to a U2F device and perform the U2F Register and U2F Authenticate
operations.")
    ;; Most files are LGPLv2.1+, but some files are GPLv3+.
    (license (list license:lgpl2.1+ license:gpl3+))))

(define-public libu2f-server
  (package
    (name "libu2f-server")
    (version "1.1.0")
    (source (origin
              (method git-fetch)
              (uri
               (git-reference
                (url "https://github.com/Yubico/libu2f-server")
                (commit (string-append "libu2f-server-" version))))
              (file-name (git-file-name name version))
              (sha256
               (base32
                "1nmsfq372zza5y6j13ydincjf324bwfcjg950vykh166xkp6wiic"))))
    (build-system gnu-build-system)
    (arguments
     `(#:configure-flags
       (list "--enable-gtk-doc"
             "--enable-tests")))
    (inputs
     `(("json-c" ,json-c-0.13)
       ("libressl" ,libressl)))
    (native-inputs
     `(("autoconf" ,autoconf)
       ("automake" ,automake)
       ("libtool" ,libtool)
       ("check" ,check)
       ("gengetopt" ,gengetopt)
       ("help2man" ,help2man)
       ("pkg-config" ,pkg-config)
       ("gtk-doc" ,gtk-doc)
       ("which" ,which)))
    (home-page "https://developers.yubico.com/libu2f-server/")
    ;; TRANSLATORS: The U2F protocol has a "server side" and a "host side".
    (synopsis "U2F server-side C library")
    (description
     "This is a C library that implements the server-side of the
@dfn{Universal 2nd Factor} (U2F) protocol.  More precisely, it provides an API
for generating the JSON blobs required by U2F devices to perform the U2F
Registration and U2F Authentication operations, and functionality for
verifying the cryptographic operations.")
    (license license:bsd-2)))

(define-public pam-u2f
  (package
    (name "pam-u2f")
    (version "1.0.8")
    (source (origin
              (method git-fetch)
              (uri
               (git-reference
                (url "https://github.com/Yubico/pam-u2f")
                (commit (string-append "pam_u2f-" version))))
              (file-name (git-file-name name version))
              (sha256
               (base32
                "04d9davyi33gqbvga1rvh9fijp6f16mx2xmnn4n61rnhcn2jac98"))))
    (build-system gnu-build-system)
    (arguments
     `(#:configure-flags
       (list (string-append "--with-pam-dir="
                            (assoc-ref %outputs "out") "/lib/security"))))
    (inputs
     `(("libu2f-host" ,libu2f-host)
       ("libu2f-server" ,libu2f-server)
       ("linux-pam" ,linux-pam)))
    (native-inputs
     `(("autoconf" ,autoconf)
       ("automake" ,automake)
       ("libtool" ,libtool)
       ("asciidoc" ,asciidoc)
       ("pkg-config" ,pkg-config)))
    (home-page "https://developers.yubico.com/pam-u2f/")
    (synopsis "PAM module for U2F authentication")
    (description
     "This package provides a module implementing PAM over U2F, providing an
easy way to integrate the YubiKey (or other U2F compliant authenticators) into
your existing infrastructure.")
    (license license:bsd-2)))

(define-public python-fido2
  (package
    (name "python-fido2")
    (version "0.5.0")
    (source (origin
              (method url-fetch)
              (uri
               (string-append
                "https://github.com/Yubico/python-fido2/releases/download/"
                version "/fido2-" version ".tar.gz"))
              (sha256
               (base32
                "1pl8d2pr6jzqj4y9qiaddhjgnl92kikjxy0bgzm2jshkzzic8mp3"))
              (snippet
               ;; Remove bundled dependency.
               #~(delete-file "fido2/public_suffix_list.dat"))))
    (build-system python-build-system)
    (arguments
     `(#:phases
       (modify-phases %standard-phases
         (add-after 'unpack 'install-public-suffix-list
           (lambda* (#:key inputs #:allow-other-keys)
             (copy-file
              (string-append (assoc-ref inputs "public-suffix-list")
                             "/share/public-suffix-list-"
                             ,(package-version public-suffix-list)
                             "/public_suffix_list.dat")
              "fido2/public_suffix_list.dat")
             #t)))))
    (propagated-inputs
     `(("python-cryptography" ,python-cryptography)
       ("python-six" ,python-six)))
    (native-inputs
     `(("python-mock" ,python-mock)
       ("python-pyfakefs" ,python-pyfakefs)
       ("public-suffix-list" ,public-suffix-list)))
    (home-page "https://github.com/Yubico/python-fido2")
    (synopsis "Python library for communicating with FIDO devices over USB")
    (description
     "This Python library provides functionality for communicating with a Fast
IDentity Online (FIDO) device over Universal Serial Bus (USB) as well as
verifying attestation and assertion signatures.  It aims to support the FIDO
Universal 2nd Factor (U2F) and FIDO 2.0 protocols for communicating with a USB
authenticator via the Client-to-Authenticator Protocol (CTAP 1 and 2).  In
addition to this low-level device access, classes defined in the
@code{fido2.client} and @code{fido2.server} modules implement higher level
operations which are useful when interfacing with an Authenticator, or when
implementing a Relying Party.")
    ;; python-fido2 contains some derivative files originally from pyu2f
    ;; (https://github.com/google/pyu2f).  These files are licensed under the
    ;; Apache License, version 2.0.  The maintainers have customized these
    ;; files for internal use, so they are not really a bundled dependency.
    (license (list license:bsd-2 license:asl2.0))))

(define-public python-yubikey-manager
  (package
    (name "python-yubikey-manager")
    (version "2.1.0")
    (source (origin
              (method url-fetch)
              (uri (string-append
                    "https://developers.yubico.com/yubikey-manager/Releases"
                    "/yubikey-manager-" version ".tar.gz"))
              (sha256
               (base32
                "11rsmcaj60k3y5m5gdhr2nbbz0w5dm3m04klyxz0fh5hnpcmr7fm"))))
    (build-system python-build-system)
    (propagated-inputs
     `(("python-six" ,python-six)
       ("python-pyscard" ,python-pyscard)
       ("python-pyusb" ,python-pyusb)
       ("python-click" ,python-click)
       ("python-cryptography" ,python-cryptography)
       ("python-pyopenssl" ,python-pyopenssl)
       ("python-fido2" ,python-fido2)))
    (inputs
     `(("yubikey-personalization" ,yubikey-personalization)
       ("pcsc-lite" ,pcsc-lite)
       ("libusb" ,libusb)))
    (native-inputs
     `(("swig" ,swig)
       ("python-mock" ,python-mock)))
    (home-page "https://developers.yubico.com/yubikey-manager/")
    (synopsis "Command line tool and library for configuring a YubiKey")
    (description
     "Python library and command line tool for configuring a YubiKey.  Note
that after installing this package, you might still need to add appropriate
udev rules to your system configuration to be able to configure the YubiKey as
an unprivileged user.")
    (license license:bsd-2)))

(define-public nitrocli
  (package
    (name "nitrocli")
    (version "0.4.1")
    (source (origin
              (method url-fetch)
              (uri (crate-uri "nitrocli" version))
              (file-name (string-append name "-" version ".tar.gz"))
              (sha256
               (base32
                "1djspfvcqjipg17v8hkph8xrhkdg1xqjhq5jk1sr8vr750yavidy"))))
    (build-system cargo-build-system)
    (arguments
     `(#:tests? #f ;; 2/164 tests fail, nitrocli-ext tests failing
       #:cargo-inputs
       (("rust-anyhow" ,rust-anyhow-1)
        ("rust-base32" ,rust-base32-0.4)
        ("rust-directories" ,rust-directories-3)
        ("rust-envy" ,rust-envy-0.4)
        ("rust-libc-0.2" ,rust-libc-0.2)
        ("rust-merge" ,rust-merge-0.1)
        ("rust-nitrokey" ,rust-nitrokey-0.9)
        ("rust-progressing" ,rust-progressing-3)
        ("rust-serde" ,rust-serde-1)
        ("rust-structopt" ,rust-structopt-0.3)
        ("rust-termion" ,rust-termion-1)
        ("rust-toml" ,rust-toml-0.5))
       #:cargo-development-inputs
       (("rust-nitrokey-test" ,rust-nitrokey-test-0.5)
        ("rust-nitrokey-test-state" ,rust-nitrokey-test-state-0.1)
        ("rust-regex" ,rust-regex-1)
        ("rust-tempfile" ,rust-tempfile-3))))
    (inputs
     `(("hidapi" ,hidapi)
       ("gnupg" ,gnupg)))
    (home-page "https://github.com/d-e-s-o/nitrocli")
    (synopsis "Command line tool for Nitrokey devices")
    (description
     "nitrocli is a program that provides a command line interface
for interaction with Nitrokey Pro, Nitrokey Storage, and Librem Key
devices.")
    (license license:gpl3+)))

(define-public ausweisapp2
  (package
    (name "ausweisapp2")
    (version "1.22.2")
    (source (origin
              (method url-fetch)
              (uri (string-append "https://github.com/Governikus/AusweisApp2/releases"
                                  "/download/" version "/AusweisApp2-" version ".tar.gz"))
              (sha256
               (base32
                "1qh1m057va7njs3yk0s31kwsvv44fjlsdac6lhiw5npcwssgjn8l"))))

    (build-system cmake-build-system)
    (native-inputs
     `(("pkg-config" ,pkg-config)
       ("qttools" ,qttools)))
    (inputs
     `(("qtbase" ,qtbase-5)
       ("qtsvg" ,qtsvg)
       ("qtdeclarative" ,qtdeclarative)
       ("qtwebsockets" ,qtwebsockets)
       ("qtgraphicaleffects" ,qtgraphicaleffects)
       ("qtquickcontrols2" ,qtquickcontrols2)
       ("pcsc-lite" ,pcsc-lite)
       ("openssl" ,openssl)))
    (arguments
     `(#:modules ((guix build cmake-build-system)
                  (guix build qt-utils)
                  (guix build utils))
       #:imported-modules (,@%cmake-build-system-modules
                           (guix build qt-utils))
       #:phases
       (modify-phases %standard-phases
         (add-after 'install 'wrap-qt
           (lambda* (#:key inputs outputs #:allow-other-keys)
             (let ((out (assoc-ref outputs "out")))
               (wrap-qt-program "AusweisApp2" #:output out #:inputs inputs)))))))
    (home-page "https://github.com/Governikus/AusweisApp2")
    (synopsis
     "Authentication program for German ID cards and residence permits")
    (description
     "This application is developed and issued by the German government to be
used for online authentication with electronic German ID cards and residence
titles.  To use this app, a supported RFID card reader or NFC-enabled smart
phone is required.")
    (license license:eupl1.2)))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2016, 2017, 2018 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2018 Tobias Geerinckx-Rice <me@tobias.gr>
;;; Copyright © 2019, 2020 Marius Bakke <mbakke@fastmail.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 selinux)
  #:use-module ((guix licenses) #:prefix license:)
  #:use-module (guix packages)
  #:use-module (guix download)
  #:use-module (guix git-download)
  #:use-module (guix utils)
  #:use-module (guix build-system gnu)
  #:use-module (guix build-system python)
  #:use-module (gnu packages)
  #:use-module (gnu packages admin)
  #:use-module (gnu packages bison)
  #:use-module (gnu packages docbook)
  #:use-module (gnu packages flex)
  #:use-module (gnu packages gettext)
  #:use-module (gnu packages glib)
  #:use-module (gnu packages linux)
  #:use-module (gnu packages networking)
  #:use-module (gnu packages pcre)
  #:use-module (gnu packages pkg-config)
  #:use-module (gnu packages python)
  #:use-module (gnu packages python-xyz)
  #:use-module (gnu packages swig)
  #:use-module (gnu packages xml))

;; Update the SELinux packages together!

(define-public libsepol
  (package
    (name "libsepol")
    (version "3.0")
    (source (let ((release "20191204"))
              (origin
                (method git-fetch)
                (uri (git-reference
                      (url "https://github.com/SELinuxProject/selinux")
                      (commit release)))
                (file-name (string-append "selinux-" release "-checkout"))
                (sha256
                 (base32
                  "05rpzm72cgprd0ccr6lvx9hm8j8b5nkqi4avshlsyg7s3sdlcxjs")))))
    (build-system gnu-build-system)
    (arguments
     `(#:tests? #f ; tests require checkpolicy, which requires libsepol
       #:test-target "test"
       #:make-flags
       (let ((out (assoc-ref %outputs "out"))
             (target ,(%current-target-system)))
         (list (string-append "PREFIX=" out)
               (string-append "SHLIBDIR=" out "/lib")
               (string-append "MAN3DIR=" out "/share/man/man3")
               (string-append "MAN5DIR=" out "/share/man/man5")
               (string-append "MAN8DIR=" out "/share/man/man8")
               (string-append "LDFLAGS=-Wl,-rpath=" out "/lib")
               (string-append "CC="
                              (if target
                                  (string-append (assoc-ref %build-inputs "cross-gcc")
                                                 "/bin/" target "-gcc")
                                  "gcc"))))
       #:phases
       (modify-phases %standard-phases
         (delete 'configure)
         (add-after 'unpack 'enter-dir
           (lambda _ (chdir ,name) #t))
         (add-after 'enter-dir 'portability
           (lambda _
             (substitute* "src/ibpkeys.c"
               (("#include \"ibpkey_internal.h\"" line)
                (string-append line "\n#include <inttypes.h>\n"))
               (("%#lx") "%#\" PRIx64 \""))
             #t)))))
    (native-inputs
     `(("flex" ,flex)))
    (home-page "https://selinuxproject.org/")
    (synopsis "Library for manipulating SELinux policies")
    (description
     "The libsepol library provides an API for the manipulation of SELinux
binary policies.  It is used by @code{checkpolicy} (the policy compiler) and
similar tools, and programs such as @code{load_policy}, which must perform
specific transformations on binary policies (for example, customizing policy
boolean settings).")
    (license license:lgpl2.1+)))

(define-public checkpolicy
  (package/inherit libsepol
    (name "checkpolicy")
    (arguments
     `(#:tests? #f ; there is no check target
       #:make-flags
       (let ((out (assoc-ref %outputs "out"))
             (target ,(%current-target-system)))
         (list (string-append "PREFIX=" out)
               (string-append "LIBSEPOLA="
                              (assoc-ref %build-inputs "libsepol")
                              "/lib/libsepol.a")
               (string-append "CC="
                              (if target
                                  (string-append (assoc-ref %build-inputs "cross-gcc")
                                                 "/bin/" target "-gcc")
                                  "gcc"))))
       #:phases
       (modify-phases %standard-phases
         (delete 'configure)
         (delete 'portability)
         (add-after 'unpack 'enter-dir
           (lambda _ (chdir ,name) #t)))))
    (inputs
     `(("libsepol" ,libsepol)))
    (native-inputs
     `(("bison" ,bison)
       ("flex" ,flex)))
    (synopsis "Check SELinux security policy configurations and modules")
    (description
     "This package provides the tools \"checkpolicy\" and \"checkmodule\".
Checkpolicy is a program that checks and compiles a SELinux security policy
configuration into a binary representation that can be loaded into the kernel.
Checkmodule is a program that checks and compiles a SELinux security policy
module into a binary representation.")
    ;; GPLv2 only
    (license license:gpl2)))

(define-public libselinux
  (package/inherit libsepol
    (name "libselinux")
    (outputs '("out" "python"))
    (arguments
     (substitute-keyword-arguments (package-arguments libsepol)
       ((#:make-flags flags)
        `(cons* "PYTHON=python3"
                (string-append "LIBSEPOLA="
                              (assoc-ref %build-inputs "libsepol")
                              "/lib/libsepol.a")
                (string-append "PYTHONLIBDIR="
                               (assoc-ref %outputs "python")
                               "/lib/python"
                               ,(version-major+minor (package-version python))
                               "/site-packages/")
                ,flags))
       ((#:phases phases)
        `(modify-phases ,phases
           (delete 'portability)
           (replace 'enter-dir
             (lambda _ (chdir ,name) #t))
           (add-after 'build 'pywrap
             (lambda* (#:key make-flags #:allow-other-keys)
               (apply invoke "make" "pywrap" make-flags)))
           (add-after 'install 'install-pywrap
             (lambda* (#:key make-flags outputs #:allow-other-keys)
               ;; The build system uses "python setup.py install" to install
               ;; Python bindings.  Instruct it to use the correct output.
               (substitute* "src/Makefile"
                 (("--prefix=\\$\\(PREFIX\\)")
                  (string-append "--prefix=" (assoc-ref outputs "python"))))

               (apply invoke "make" "install-pywrap" make-flags)))))))
    ;; These libraries are in "Requires.private" in libselinux.pc.
    (propagated-inputs
     `(("libsepol" ,libsepol)
       ("pcre" ,pcre)))
    ;; For pywrap phase
    (inputs
     `(("python" ,python-wrapper)))
    ;; These inputs are only needed for the pywrap phase.
    (native-inputs
     `(("swig" ,swig)
       ("pkg-config" ,pkg-config)))
    (synopsis "SELinux core libraries and utilities")
    (description
     "The libselinux library provides an API for SELinux applications to get
and set process and file security contexts, and to obtain security policy
decisions.  It is required for any applications that use the SELinux API, and
used by all applications that are SELinux-aware.  This package also includes
the core SELinux management utilities.")
    (license license:public-domain)))

(define-public libsemanage
  (package/inherit libsepol
    (name "libsemanage")
    (arguments
     (substitute-keyword-arguments (package-arguments libsepol)
       ((#:make-flags flags)
        `(cons* "PYTHON=python3"
                (string-append "PYTHONLIBDIR="
                               (assoc-ref %outputs "out")
                               "/lib/python"
                               ,(version-major+minor (package-version python))
                               "/site-packages/")
                ,flags))
       ((#:phases phases)
        `(modify-phases ,phases
           (delete 'portability)
           (replace 'enter-dir
             (lambda _ (chdir ,name) #t))
           (add-before 'install 'adjust-semanage-conf-location
             (lambda _
               (substitute* "src/Makefile"
                 (("DEFAULT_SEMANAGE_CONF_LOCATION=/etc")
                  "DEFAULT_SEMANAGE_CONF_LOCATION=$(PREFIX)/etc"))
               #t))
           (add-after 'build 'pywrap
             (lambda* (#:key make-flags #:allow-other-keys)
               (apply invoke "make" "pywrap" make-flags)))
           (add-after 'install 'install-pywrap
             (lambda* (#:key make-flags #:allow-other-keys)
               (apply invoke "make" "install-pywrap" make-flags)))))))
    (inputs
     `(("libsepol" ,libsepol)
       ("libselinux" ,libselinux)
       ("audit" ,audit)
       ;; For pywrap phase
       ("python" ,python-wrapper)))
    (native-inputs
     `(("bison" ,bison)
       ("flex" ,flex)
       ;; For pywrap phase
       ("swig" ,swig)
       ("pkg-config" ,pkg-config)))
    (synopsis "SELinux policy management libraries")
    (description
     "The libsemanage library provides an API for the manipulation of SELinux
binary policies.")
    (license license:lgpl2.1+)))

(define-public secilc
  (package/inherit libsepol
    (name "secilc")
    (arguments
     (substitute-keyword-arguments (package-arguments libsepol)
       ((#:make-flags flags)
        `(let ((docbook (assoc-ref %build-inputs "docbook-xsl")))
           (cons (string-append "XMLTO=xmlto --skip-validation -x "
                                docbook "/xml/xsl/docbook-xsl-"
                                ,(package-version docbook-xsl)
                                "/manpages/docbook.xsl")
                 ,flags)))
       ((#:phases phases)
        `(modify-phases ,phases
           (delete 'portability)
           (replace 'enter-dir
             (lambda _ (chdir ,name) #t))))))
    (inputs
     `(("libsepol" ,libsepol)))
    (native-inputs
     `(("xmlto" ,xmlto)
       ("docbook-xsl" ,docbook-xsl)))
    (synopsis "SELinux common intermediate language (CIL) compiler")
    (description "The SELinux CIL compiler is a compiler that converts the
@dfn{common intermediate language} (CIL) into a kernel binary policy file.")
    (license license:bsd-2)))

(define-public python-sepolgen
  (package/inherit libsepol
    (name "python-sepolgen")
    (arguments
     `(#:modules ((srfi srfi-1)
                  (guix build gnu-build-system)
                  (guix build utils))
       ,@(substitute-keyword-arguments (package-arguments libsepol)
           ((#:phases phases)
            `(modify-phases ,phases
               (delete 'portability)
               (replace 'enter-dir
                 (lambda _ (chdir "python/sepolgen") #t))
               ;; By default all Python files would be installed to
               ;; $out/gnu/store/...-python-.../, so we override the
               ;; PACKAGEDIR to fix this.
               (add-after 'enter-dir 'fix-target-path
                 (lambda* (#:key inputs outputs #:allow-other-keys)
                   (let ((get-python-version
                          ;; FIXME: copied from python-build-system
                          (lambda (python)
                            (let* ((version     (last (string-split python #\-)))
                                   (components  (string-split version #\.))
                                   (major+minor (take components 2)))
                              (string-join major+minor ".")))))
                     (substitute* "src/sepolgen/Makefile"
                       (("^PACKAGEDIR.*")
                        (string-append "PACKAGEDIR="
                                       (assoc-ref outputs "out")
                                       "/lib/python"
                                       (get-python-version
                                        (assoc-ref inputs "python"))
                                       "/site-packages/sepolgen")))
                     (substitute* "src/share/Makefile"
                       (("\\$\\(DESTDIR\\)") (assoc-ref outputs "out"))))
                   #t)))))))
    (inputs
     `(("python" ,python-wrapper)))
    (native-inputs '())
    (synopsis "Python module for generating SELinux policies")
    (description
     "This package contains a Python module that forms the core of
@code{audit2allow}, a part of the package @code{policycoreutils}.  The
sepolgen library contains: Reference Policy Representation, which are Objects
for representing policies and the reference policy interfaces.  It has objects
and algorithms for representing access and sets of access in an abstract way
and searching that access.  It also has a parser for reference policy
\"headers\".  It contains infrastructure for parsing SELinux related messages
as produced by the audit system.  It has facilities for generating policy
based on required access.")
    ;; GPLv2 only
    (license license:gpl2)))

(define-public python-setools
  (package
    (name "python-setools")
    (version "4.1.1")
    (source (origin
              (method git-fetch)
              (uri (git-reference
                    (url "https://github.com/TresysTechnology/setools")
                    (commit version)))
              (file-name (string-append name "-" version "-checkout"))
              (sha256
               (base32
                "0459xxly6zzqc5azcwk3rbbcxvj60dq08f8z6xr05y7dsbb16cg6"))))
    (build-system python-build-system)
    (arguments
     `(#:tests? #f ; the test target causes a rebuild
       #:phases
       (modify-phases %standard-phases
         (delete 'portability)
         (add-after 'unpack 'set-SEPOL-variable
           (lambda* (#:key inputs #:allow-other-keys)
             (setenv "SEPOL"
                     (string-append (assoc-ref inputs "libsepol")
                                    "/lib/libsepol.a"))))
         (add-after 'unpack 'remove-Werror
           (lambda _
             (substitute* "setup.py"
               (("'-Werror',") ""))
             #t))
         (add-after 'unpack 'fix-target-paths
           (lambda* (#:key outputs #:allow-other-keys)
             (substitute* "setup.py"
               (("join\\(sys.prefix")
                (string-append "join(\"" (assoc-ref outputs "out") "/\"")))
             #t)))))
    (propagated-inputs
     `(("python-networkx" ,python-networkx)))
    (inputs
     `(("libsepol" ,libsepol)
       ("libselinux" ,libselinux)))
    (native-inputs
     `(("bison" ,bison)
       ("flex" ,flex)
       ("swig" ,swig)))
    (home-page "https://github.com/TresysTechnology/setools")
    (synopsis "Tools for SELinux policy analysis")
    (description "SETools is a collection of graphical tools, command-line
tools, and libraries designed to facilitate SELinux policy analysis.")
    ;; Some programs are under GPL, all libraries under LGPL.
    (license (list license:lgpl2.1+
                   license:gpl2+))))

(define-public policycoreutils
  (package/inherit libsepol
    (name "policycoreutils")
    (arguments
     `(#:test-target "test"
       #:make-flags
       (let ((out (assoc-ref %outputs "out")))
         (list "CC=gcc"
               (string-append "PREFIX=" out)
               (string-append "LOCALEDIR=" out "/share/locale")
               (string-append "BASHCOMPLETIONDIR=" out
                              "/share/bash-completion/completions")
               "INSTALL=install -c -p"
               "INSTALL_DIR=install -d"
               ;; These ones are needed because some Makefiles define the
               ;; directories relative to DESTDIR, not relative to PREFIX.
               (string-append "SBINDIR=" out "/sbin")
               (string-append "ETCDIR=" out "/etc")
               (string-append "SYSCONFDIR=" out "/etc/sysconfig")
               (string-append "MAN5DIR=" out "/share/man/man5")
               (string-append "INSTALL_NLS_DIR=" out "/share/locale")
               (string-append "AUTOSTARTDIR=" out "/etc/xdg/autostart")
               (string-append "DBUSSERVICEDIR=" out "/share/dbus-1/services")
               (string-append "SYSTEMDDIR=" out "/lib/systemd")
               (string-append "INITDIR=" out "/etc/rc.d/init.d")
               (string-append "SELINUXDIR=" out "/etc/selinux")))
       #:phases
       (modify-phases %standard-phases
         (delete 'configure)
         (delete 'portability)
         (add-after 'unpack 'enter-dir
           (lambda _ (chdir ,name) #t))
         (add-after 'enter-dir 'ignore-/usr-tests
           (lambda* (#:key inputs #:allow-other-keys)
             ;; Rewrite lookup paths for header files.
             (substitute* '("newrole/Makefile"
                            "setfiles/Makefile"
                            "run_init/Makefile")
               (("/usr(/include/security/pam_appl.h)" _ file)
                (string-append (assoc-ref inputs "pam") file))
               (("/usr(/include/libaudit.h)" _ file)
                (string-append (assoc-ref inputs "audit") file)))
             #t)))))
    (inputs
     `(("audit" ,audit)
       ("pam" ,linux-pam)
       ("libsepol" ,libsepol)
       ("libselinux" ,libselinux)
       ("libsemanage" ,libsemanage)))
    (native-inputs
     `(("gettext" ,gettext-minimal)))
    (synopsis "SELinux core utilities")
    (description "The policycoreutils package contains the core utilities that
are required for the basic operation of an SELinux-enabled GNU system and its
policies.  These utilities include @code{load_policy} to load policies,
@code{setfiles} to label file systems, @code{newrole} to switch roles, and
@code{run_init} to run service scripts in their proper context.")
    (license license:gpl2+)))