#!/bin/bash

printf "Installing CP SSH Handler...\n"

printf "  - Creating desktop entry..."
{
        echo "[Desktop Entry]"
        echo "Type=Application"
        echo "Name=CP SSH Handler"
        echo "Exec=cp_ssh_handler.sh %u"
        echo "Icon=utilities-terminal"
        echo "StartupNotify=false"
        echo "MimeType=text/html;x-scheme-handler/ssh"
} > ~/.local/share/applications/cp_ssh_handler.desktop
printf "DONE\n"

printf "  - Creating handler script..."
{
        echo "#!/bin/bash"
        echo ""
        echo "url=\$1"
        echo "protocol=\$(echo \"\${url}\" | cut -d':' -f1)"
        echo "address=\$(echo \"\${url}\" | cut -d'/' -f3)"
        echo ""
        echo "if [[ \${protocol} != \"ssh\" ]]"
        echo "then"
        echo "  echo \"Protocol \${protocol} not supported!\""
        echo "  exit 1"
        echo "fi"
        echo ""
        echo "TERM_BIN=\$(which gnome-terminal)"
        echo "if [[ ! -z \${TERM_BIN} ]]"
        echo "then"
        echo "  \${TERM_BIN} -- \${protocol} \${address}"
        echo "else"
        echo "  echo \"Unknown terminal application!\""
        echo "fi"
} > ~/.local/bin/cp_ssh_handler.sh
chmod +x ~/.local/bin/cp_ssh_handler.sh
printf "DONE\n"

printf "  - Registering handler..."
xdg-settings set default-url-scheme-handler ssh cp_ssh_handler.desktop
printf "DONE\n"
