#! /bin/sh
exec guile -s "$0" "$@" ; -*- scheme -*-
!#


#!/usr/bin/guile -s
!#
;;     This file is part of cdloop
;;     Copyright (C) 2001-2003 Claus Brunzema <mail@cbrunzema.de>
;; 
;;     This program 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 2 of the License, or
;;     (at your option) any later version.
;; 
;;     This program 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 this program; if not, write to the Free Software
;;     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
;; 

(use-modules (ice-9 regex))

(define socket-dir (string-append "/tmp/cdloop-" (getenv "USER")))
(define socket-file (string-append socket-dir "/cdloop"))

(define (show-help)
  (display "
cdloop-remote - send commands to a running cdloop process

Usage: cdloop-remote [options] <form>

Let a running cdloop process execute FORM. All newlines in FORM
will be substituted with spaces.

Example:

$ cdloop-remote '(play-track 2)'

will cause cdloop to play track #2. Note the quotes to protect the
parentheses from the shell.

Options:
        -h, --help     show help message.
        -v, --version  show version info.
")
  (newline)
  (quit))

(define (show-version)
  (display "cdloop-remote 3.1.0")
  (newline)
  (quit))


(if (null?  (cdr (command-line)))
    (show-help))


;;;- main -----------------------------------------------------------------
(let ((arg (cadr (command-line))))
  (cond
   ((or (string=? "-h" arg)
        (string=? "--help" arg))
    (show-help))
   ((or (string=? "-v" arg)
        (string=? "--version" arg))
    (show-version))
   (t
    (if (not (access? socket-file W_OK))
        (begin
          (display (string-append "Can't write to " socket-file ". Abort."))
          (newline)
          (quit)))
    (let ((sock (socket AF_UNIX SOCK_STREAM 0)))
      (connect sock AF_UNIX socket-file)
      (display
       (regexp-substitute/global #f "\n" (cadr (command-line)) 'pre " " 'post)
       sock)
      (newline sock)
      (close-port sock)))))
