--   This file is part of Reno desktop.
--
--  Reno desktop is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
--
--  Reno desktop is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
--
--  You should have received a copy of the GNU General Public License along with Reno desktop. If not, see <https://www.gnu.org/licenses/>. 
-- If you experience errors on the next line,
-- that means that you did not install lua-pam.
-- Run install_luapam.sh from the various-scripts directory.
local pam = require('pam')
local naughty = require("naughty")

local function check_password(pw,username)
    local function conversation(messages)
        local responses = {}
        for i, message in ipairs(messages) do
            local msg_style, msg = message[1], message[2] 
            if msg_style == pam.PROMPT_ECHO_OFF then
                -- Assume PAM asks us for the password
                print("PAM Message: ",msg)
                responses[i] = {pw, 0}
            elseif msg_style == pam.PROMPT_ECHO_ON then
                -- Assume PAM asks us for the username
                print("PAM Message: ",msg)
                responses[i] = {username or os.getenv("USER"), 0}
            elseif msg_style == pam.ERROR_MSG then
                print("PAM Error: ",msg)
                responses[i] = {"", 0}
            elseif msg_style == pam.TEXT_INFO then
                print("PAM Info message: ",msg)
                responses[i] = {"", 0}
            else
                print("Unsupported conversation message style for PAM: " .. msg_style)
                print("PAM Message: ",msg)
            end
        end
        return responses
    end
    local handler,err = pam.start("system-auth", nil, {conversation, nil})
    if not handler then
        naughty.notify({title="PAM session start error: ",text=err,bg="#AA0000"})
        print("PAM session start error: ",err)
        return false
    end
    local auth,err = pam.authenticate(handler)
    if not auth then
        print("PAM authentication error: ",err)
        return false
    end
    local s_end,err = pam.endx(handler, pam.SUCCESS)
    if not s_end then
        naughty.notify({title="PAM session end error: ",text=err,bg="#AA0000"})
        print("PAM session end error: ",err)
        return false
    end
    return true
end
return check_password
