--display notification "Please wait... preparing login process..." with title "LastPass Login"

--Kill any previous login process as sometimes they hang or a user may interrupt them, if there are none (which there often are...) we will get an error response which we ignore.
try
	do shell script "killall -9 lpass > /dev/null 2>&1"
end try

try
	set login_email to do shell script "`perl -e 'use strict; use warnings; my $emailAddress =`security find-generic-password -w -s \"alfred-lastpass-email-address\"`; chomp $emailAddress; print $emailAddress;'`"
on error
	display alert "Email address not set" message "It appears that no email address has been set. Please run 'lpsetemail your_email@example.com' and try again." as critical
	return
end try

--Try to get a login timeout if a custom one has been set, if not we set to default
try
	set login_timeout to do shell script "`perl -e 'use strict; use warnings; my $loginTimeout =`security find-generic-password -w -s \"alfred-lastpass-login-timeout\"`; chomp $loginTimeout; print $loginTimeout;'`"
on error
	set login_timeout to 28800
end try

tell application "Finder"
	set current_path to container of (path to me) as alias
end tell
set current_unix_path to POSIX path of current_path

--set osascript to current_unix_path & "passwordInput.osascript"

set osascript to (system attribute "alfred_preferences") & "/workflows/" & (system attribute "alfred_workflow_uid") & "/passwordInput.osascript"

try
	do shell script "mkdir \"" & (system attribute "alfred_workflow_data") & "\""
end try

do shell script "echo \"" & osascript & "\" > \"" & (system attribute "alfred_workflow_data") & "/running_location.txt\""

do shell script "export LPASS_ASKPASS=\"" & osascript & "\""
do shell script "launchctl setenv LPASS_ASKPASS \"" & osascript & "\""

do shell script "launchctl setenv LPASS_AGENT_TIMEOUT " & login_timeout

tell application "Finder"
	if exists POSIX file "/usr/bin/lpass" then
		set lpass_binary to "/usr/bin/lpass"
	else if exists POSIX file "/usr/local/bin/lpass" then
		set lpass_binary to "/usr/local/bin/lpass"
	else if exists POSIX file "/opt/local/bin/lpass" then
		set lpass_binary to "/opt/local/bin/lpass"
	end if
end tell

--improvement required here, test if we actually HAVE an lpass_binary and if not error out

if ("{query}" = "scriptlocationnotset") then
display notification "Please wait... the alfred search will be presented once login is complete." with title "LastPass Login"
end if

do shell script "/bin/bash -c '" & "export TERM=\"xterm-256color\" && export LPASS_ASKPASS=\"" & osascript & "\" && export LPASS_AGENT_TIMEOUT=" & login_timeout & " && " & lpass_binary & " login --trust \"" & login_email & "\" && clear && " & lpass_binary & " ls --sync=now > /dev/null 2>&1 && exit 0'"

if ("{query}" = "scriptlocationnotset") then
--@squatto: line changed from original: tell application "Alfred 3" to search "lp "
tell application id "com.runningwithcrayons.Alfred" to search "lp "
end if