#!/usr/bin/env -S guile --no-auto-compile -e (ssh-aliases) -s
!#

;;;; ssh-aliases --- SYNOPSIS
;;;; Copyright © 2020 Oleg Pykhalov <go.wigust@gmail.com>
;;;; Released under the GNU GPLv3 or any later version.

(define-module (ssh-aliases)
  #:use-module (ice-9 match)
  #:use-module (ice-9 rdelim)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-37)
  #:export (main))

;;; Commentary:
;;;
;;; DESCRIPTION
;;;
;;; Code:

(define %options
  (let ((display-and-exit-proc (lambda (msg)
                                 (lambda (opt name arg loads)
                                   (display msg) (quit)))))
    (list (option '(#\v "version") #f #f
                  (display-and-exit-proc "ssh-aliases version 0.0.1\n"))
          (option '(#\h "help") #f #f
                  (display-and-exit-proc
                   "Usage: ssh-aliases ...")))))

(define %default-options
  '())

(define %know-hosts
  (and=> (getenv "HOME")
         (lambda (home)
           (string-append home "/.ssh/known_hosts"))))

(define %command
  (or (and=> (getenv "SSH_COMMAND") (lambda (command) command))
      "ssh"))

(define (main args)
  (for-each (lambda (host)
              (format #t "alias ~a=~s~%"
                      (if (string-suffix? ".intr" host)
                          (string-drop-right host (string-length ".intr"))
                          host)
                      (format #f "~a ~a" %command host))
              (format #t "complete -W ~s ~a~%"
                      "apache block clean containers images mysql nginx ping sg status te traceroute"
                      (string-drop-right host (string-length ".intr"))))
            (sort (filter (cut string-suffix? ".intr" <>)
                          (map (match-lambda ((host _ ...) host))
                               (map (cut string-split <> #\space)
                                    (string-split (with-input-from-file %know-hosts read-string)
                                                  #\newline))))
                  string<)))

;;; ssh-aliases ends here
