#!/usr/bin/env -S guile --no-auto-compile -e main -s
!#

(use-modules (srfi srfi-1)
             (ice-9 format)
             (web uri))

(define xdg-open
  "/run/current-system/profile/bin/xdg-open")

(define (notify str)
  (system (format #f "notify-send ~s" str)))

(define (main args)
  (let ((arg (last args)))
    (if (string-prefix? "http" arg)
        (let* ((uri (string->uri arg))
               (host (uri-host uri)))
          (cond
           ((string-prefix? host "imgur.com")
            (notify (format #f "Open in feh ~a" arg))
            (system (format #f "curl --silent ~s | feh -"
                            (uri->string (build-uri 'https
                                                    #:host (string-append "i." host)
                                                    #:path (uri-path uri))))))
           ((string-prefix? host "cdn.discordapp.com")
            (notify (format #f "Open in feh ~a" arg))
            (system (format #f "curl --silent ~s | feh -" arg)))
           ((or (string-prefix? host "www.twitch.tv")
                (string-contains host "youtube.com"))
            (notify (format #f "Open in mpv ~a" arg))
            (system (format #f "mpv ~s" arg)))
           (else (execl "/run/current-system/profile/bin/xdg-open" "xdg-open" arg))))
        (execl "/run/current-system/profile/bin/xdg-open" "xdg-open" arg))))
