local system = require 'system'
local fs = require 'filesystem'
local pipe = require 'pipe'
local stream = require 'stream'
local util = require '../common'

local function run_filter(arguments, input, environment)
    local child_input, host_output = pipe.pair()
    local host_input, child_output = pipe.pair()
    child_input = child_input:release()
    child_output = child_output:release()

    local process = system.spawn{
        program = 'gpg',
        arguments = arguments,
        environment = environment,
        stdin = child_input,
        stdout = child_output,
        stderr = 'share',
    }
    child_input:close()
    child_output:close()

    local writer = spawn(function()
        stream.write_all(host_output, input)
        host_output:close()
    end)
    local reader = spawn(function()
        return util.read_to_eof(host_input)
    end)

    process:wait()
    writer:join()
    local output = reader:join()
    if process.exit_code ~= 0 then
        error('gpg exited with status ' .. process.exit_code)
    end
    return output
end

local gnupg_home = fs.temp_directory_path() / ('emilua-gpg-' .. system.getpid())
fs.create_directories(gnupg_home)
fs.chmod(gnupg_home, fs.mode(7, 0, 0))

local environment = system.environment
environment.GNUPGHOME = tostring(gnupg_home)

local ok, err = xpcall(function()
    local plaintext = 'Emilua can orchestrate processes and pipes.'
    local encrypted = run_filter(
        {'gpg', '--batch', '--yes', '--pinentry-mode', 'loopback',
         '--passphrase', 'website-demo', '--symmetric'},
        plaintext, environment)
    local decrypted = run_filter(
        {'gpg', '--batch', '--yes', '--pinentry-mode', 'loopback',
         '--passphrase', 'website-demo', '--decrypt'},
        encrypted, environment)

    assert(decrypted == plaintext)
    print('GPG round trip: ' .. decrypted)
end, function(err) return err end)

fs.remove_all(gnupg_home)
if not ok then
    error(err)
end
