#!/usr/bin/newlisp
#
# This is a test script for the overlay function of fusefile.
#
# 1) prepare a base image
# 2) set up a fusefile overlay
# 3) run tests
# 4) dismantle the fusefile overlay
# 5) remove test images

; ID is hour, minute and second values packed into a string
(constant
 'ID (apply string (3 3 (now)))
 'BASE (format "%s.raw" ID)
 'OLY (format "%s.oly" ID)
 'SEGSZ 17000
 'SEGN 40
 )

(constant
 'LIBC6 "/lib/x86_64-linux-gnu/libc.so.6"
 'MINE "mine"
 )

(import LIBC6 "on_exit" "int" "void*" "void*")

;; Set up a fusefile
(define (onexit x y)
  (write-line 2 (string "terminating: " x " " (get-string y)))
  (! (format "fusermount -u %s" BASE))
  (delete-file OLY)
  (delete-file BASE)
  )
## note: BASE is set up as a holes file with SEGN segments of size SEGSZ
(! (format "dd if=/dev/zero of=%s bs=%d seek=%d count=0 status=none"
           BASE SEGSZ SEGN))
(unless (= (! (format "fusefile %s %s -overlay:%s %s"
                      "-ononempty -oallow_other" BASE OLY BASE)))
  (exit 1))
(on_exit (callback 'onexit "void" "int" "void*") MINE)

(println (list BASE OLY))

(define (die) (write-line 2 (apply string (args))))

(define (prog1 x) x)

(define (pos X (OFF 0))
  (+ (* SEGSZ X) OFF))

(define (read-segment FILE X (OFF 0) (N SEGSZ))
  (let ((FD (open FILE "r")) (BUFFER ""))
    (seek FD (pos X OFF))
    (prog1 (when (= N (read FD BUFFER N)) BUFFER)
      (close FD))))

(define (write-segment FILE X DATA (OFF 0))
  (let ((FD (open FILE "u")))
    (seek FD (pos X OFF))
    (write FD DATA)
    ;(seek FD -1)
    (close FD)))

(define (read-ulong FD)
  (let ((BUFFER ""))
    (when (= 8 (read FD BUFFER 8)) ((unpack "ld" BUFFER) 0))))

(define (read-table)
  (let ((AT (file-info BASE 0)) (FD (open OLY "r")) (COUNT 0) (OUT '()))
    (seek FD AT)
    (unless (setf COUNT (read-ulong FD))
      (write-line 2 "** Bad count")
      (exit 1))
    (push COUNT OUT -1)
    (dotimes (i COUNT)
      (push (list (read-ulong FD) (read-ulong FD)) OUT -1))
    OUT))

(define (check-segment AT DATA (OFF 0))
  (write-segment BASE AT DATA OFF)
  (println
   (format "check %2d %d: %s %s %s" AT
           (length DATA)
           (if (= (read-segment BASE AT OFF (length DATA)) DATA) "ok" "error")
           (if (= (read-segment OLY AT OFF (length DATA)) DATA) "ok" "error")
           (string (read-table))))
  )
  
;; Test 1
(seed (date-value))
(setf
 DATA (pack (dup "b" SEGSZ) (rand 256 SEGSZ))
 DATB (pack (dup "b" (* 4 SEGSZ)) (rand 256 (* 4 SEGSZ)))
 AT (- SEGN 4))
(check-segment 0 DATA 0)

(check-segment AT DATA)
(check-segment (+ AT 2) DATA)
(check-segment (+ AT 1) DATA)
(check-segment (- AT 1) DATA -10)
(check-segment (- AT 1) DATA 10)

(check-segment 0 DATA 0)
(check-segment 1 DATA 1)
(check-segment 2 DATA 2)
(check-segment 0 DATB 10)

(check-segment (- SEGN 1) DATA 0)

;(setf DATA (pack (dup "b" SEGSZ) (rand 256 SEGSZ)) AT (- SEGN 4))

(exit 0)
