#!/usr/bin/env osascript
# Copyright (c) 2014-, Johan Wassberg <johan@rymdvarel.se>
# Copyright (c) 2011-, Simon Lundström <simmel@soy.se>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.

on run argv
    set args to argv as text
    considering numeric strings
        set pre_catalina to (system version of (system info)) < "10.15"
    end considering
    if pre_catalina then
        set agent to POSIX file "/Applications/Utilities/Terminal.app/Contents/Resources/Terminal.icns"
    else
        set agent to POSIX file "/System/Applications/Utilities/Terminal.app/Contents/Resources/Terminal.icns"
    end if
    set dialog_timeout to 15

    set prompt to system attribute "SSH_ASKPASS_PROMPT"
    # prompt = "confirm" is the same as our else, so just let it pass though
    if prompt is "none" then
        display dialog args with icon agent default button 1 buttons { "OK" }
    else if args ends with ": " or args ends with ":" then
        if args contains "pass" or args contains "pin" then
            display dialog args with icon agent default button 2 default answer "" with hidden answer
        else
            display dialog args with icon agent default button 2 default answer ""
        end if
        return result's text returned
    else if args contains " host " then
        display dialog args with icon agent default button 1 cancel button 2 buttons {"OK", "No", "Yes"} default answer ""
        set host_key_result to result
        if text returned of host_key_result is not "" then
            return text returned of host_key_result
        else
            return button returned of host_key_result
        end if
    else
        display dialog args with icon agent default button 1 giving up after dialog_timeout
        if gave up of result then
            error result
        end if
    end if
end run
