#!/usr/bin/env sh
:$(); # -*- mode: clojure -*-
:$(); exit=0
:$(); bb --init "$0" -- "$@" || exit=$?
:$(); exit $exit
(ns vpn-tools
  (:require [babashka.cli :as cli]
            [babashka.process :as p]
            [babashka.http-client :as http])
  (:import [clojure.lang ExceptionInfo]))

(defn adorn-with-help-option [spec]
  (letfn [(fn-with-help [opts]
            ;; TODO: Implement
            ((:fn spec) opts))]
    (-> spec
        (assoc-in [:spec :help]
                  {:help {:coerce :bool}})
        (assoc :fn fn-with-help))))

(defn help [opts]
  (prn 'help))

(defn vpn-shell [opts]
  (let [cmd (or (:args opts) ["bash"])
        user (System/getenv "USER")
        namespace (-> opts :opts :namespace)
        ip-cmd (concat ["sudo" "ip" "netns" "exec"
                        namespace "sudo" "-u" user]
                       cmd)]
    (apply println "$" ip-cmd)
    (-> (apply p/shell ip-cmd)
        :exit System/exit)))

(defn test-mullvad [_opts]
  (p/shell "curl https://am.i.mullvad.net/connected"))

(def namespace-option
  {:namespace {:coerce :string
               :alias :n
               :default "wg"
               :ref "NAMESPACE"}})

(def cli-table
  (map adorn-with-help-option
       [{:cmds ["shell"]
         :fn vpn-shell
         :spec namespace-option}
        {:cmds ["test-mullvad"]
         :fn test-mullvad}
        {:cmds []
         :fn help}]))

(defn -main [& args]
  (cli/dispatch cli-table args))

#_
(apply -main *command-line-args*)
