#!/bin/bash
# Daniel Napora 2021 <napcok@gmail.com>
#: jgssh - pipemenu for connecting to hosts defined in ~/.ssh/config
#: Usage: jgssh ( )
#:
#:
case $LANG in
    pl*)
    SSH_CONN="Połączenia SSH"
    CONNECT="Połącz z"
    TERM="Terminal"
    FM="Menadżer plików"
    REMOVE="Usuń to menu z panelu"
    EDIT="Edytuj"
    ;;
    es*)
    SSH_CONN="Hosts SSH"
    CONNECT="Conectar a"
    TERM="Terminal"
    FM="Gestor de archivos"
    REMOVE="Eliminar este menú del panel"
    EDIT="Editar"
    ;;
    *)
    SSH_CONN="SSH hosts"
    CONNECT="Connect to"
    TERM="Terminal"
    FM="File Manager"
    REMOVE="Remove this menu from panel"
    EDIT="Edit"
    ;;
esac
mkdir -p "$HOME/.ssh"

__usage() {
    grep "^#:" $0 | while read DOC; do printf '%s\n' "${DOC###:}"; done
    exit
}

__mklist() {
hostlist=$(sed -ne 's/^[[:blank:]]*[Hh][Oo][Ss][Tt][[:blank:]]\{1,\}\([^#*?%]*\)\(#.*\)\{0,1\}$/\1/p' ~/.ssh/config)
out+=("^sep($SSH_CONN)")
for host in $hostlist;
do 
out+=("$host,^checkout($host)")
out2+=("^tag($host)")
out2+=("^sep($CONNECT $host)")
out2+=("<big></big> $TERM,^term(ssh $host)")
out2+=(" $FM,pcmanfm $HOME sftp://$host/")
done
out+=("^sep()")
out+=("$EDIT <i>~/.ssh/config</i>, xdg-open $HOME/.ssh/config")
}

__removable() {
    __mklist
    out+=("^sep()")
    out+=("<i>$REMOVE</i>,mb-setvar places_sshpipe=false;mb-jgtools places")
    __ret
}

__standalone() {
    __mklist
. /usr/share/mb-jgtools/pipemenu-standalone.cfg
. $HOME/.config/mabox/mabox.conf

if [[ $panels_heightpos == "top" ]]; then
MENU_VALIGN="top"
MENU_MARGIN_Y=${panels_topmargin:-0}
elif [[ $panels_heightpos == "bottom" ]]; then
MENU_VALIGN="bottom"
MENU_MARGIN_Y=${panels_topmargin:-0}
else 
    MENU_VALIGN="center"
fi
MENU_PADDING_TOP=${jgtools_padding:-0}
MENU_HALIGN="left"
MENU_MARGIN_Y=40
jgmenu_icon_size=0
menu_margin_x=${submenu_spacing:-0}
[ $(pidof picom) ] && MENU_RADIUS=$jgtools_radius
[ -z $jgmenu_use_borders ] && menu_border=0

mkconfigfile

cat <<EOF > ${MENU_ITEMS}

$(printf '%s\n' "${out[@]}")
$(printf '%s\n' "${out2[@]}")
EOF

jgmenu --config-file=${CONFIG_FILE} --csv-file=${MENU_ITEMS} 2>/dev/null

exit 0

}

__ret() {
  printf '%s\n' "${out[@]}"
  printf '%s\n' "${out2[@]}"
}


case "$1" in
    "-r") __removable ;;
    "-s") __standalone ;;
    "-h"|"--help") __usage ;;
    *) __usage ;;
esac

exit 0
