;;; Gash -- Guile As SHell
;;; Copyright © 2019 Timothy Sample <samplet@ngyro.com>
;;;
;;; This file is part of Gash.
;;;
;;; Gash 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.
;;;
;;; Gash 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 Gash.  If not, see <http://www.gnu.org/licenses/>.

(current-warning-port (open-output-file "/dev/null"))
(define-module (gash compat)
  #:use-module (ice-9 match)
  #:export (if-guile-version-below))

;;; Commentary:
;;;
;;; This module fills in for features that are missing in older
;;; versions of the '(guile)' module.
;;;
;;; Code:

(define-syntax if-guile-version-below
  (lambda (x)
    (define (guile-version<? major minor micro)
      (let ((g-major (string->number (major-version)))
            (g-minor (string->number (minor-version)))
            (g-micro (string->number (micro-version))))
        (or (< g-major major)
            (and (= g-major major)
                 (< g-minor minor))
            (and (= g-major major)
                 (= g-minor minor)
                 (< g-micro micro)))))

    (syntax-case x ()
      ((_ (maj min mic) consequent alternate)
       (if (guile-version<? (syntax->datum #'maj)
                            (syntax->datum #'min)
                            (syntax->datum #'mic))
           #'consequent
           #'alternate))
      ((_ (maj min mic) consequent)
       #'(if-guile-version-below (maj min mic)
           consequent
           (if #f #t))))))

(if-guile-version-below (2 0 15)
  (begin
    (define-public EXIT_SUCCESS 0)

    (define-public EXIT_FAILURE 1)

    (define-public (exact-integer? x)
      (and (integer? x) (exact? x)))))

(if-guile-version-below (2 2 0)
  (begin
    (define* (setvbuf port mode #:optional size)
      (let ((mode (match mode
                    ('none _IONBF)
                    ('line _IOLBF)
                    ('block _IOFBF))))
        ((@ (guile) setvbuf) port mode size)))
    (export! setvbuf)))
