#!/usr/bin/lua

--! LibreMesh
--! Copyright (C) 2019  Marcos Gutierrez <gmarcos@altermundi.net>
--! Copyright (C) 2019  Luandro <luandro@gmail.com>
--! Copyright (C) 2020  Santiago Piccinini <spiccinini@altermundi.net>
--!
--! This program is free software: you can redistribute it and/or modify
--! it under the terms of the GNU Affero General Public License as
--! published by the Free Software Foundation, either version 3 of the
--! License, or (at your option) any later version.
--!
--! This program 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 Affero General Public License for more details.
--!
--! You should have received a copy of the GNU Affero General Public License
--! along with this program.  If not, see <http://www.gnu.org/licenses/>.

local json = require("luci.jsonc")
local vouchera = require("voucher.vouchera")

local function shell(command)
    local handle = io.popen(command)
    local result = handle:read("*a")
    handle:close()
    return result
end

vouchera.init()

--! The idea is to put voucher modifications into new keys of the shared-state db.
--! So a vocher may be in multiple keys of the shared-state database but the "old"
--! keys will die beacause of the bleachTTL when all the nodes pick up the last updated
--! version of the voucher.
local result = {}
for _, voucher in pairs(vouchera.vouchers) do
    local text = voucher.tostring()
    local hash = shell('echo "'..text..'" | md5sum | cut -c -8'):gsub("\n","")
    result[hash] = voucher
end

io.popen("shared-state insert pirania-vouchers", "w"):write(json.stringify(result))
