#!/usr/bin/env hilbish

-- Note: this script only supports 1 Vivaldi install.

local posix = require("posix")
local fs = require("fs")

local _, mod_dir = posix.pwd()
mod_dir = mod_dir:gsub("\n", "") .. "/js"
local custom_js = mod_dir .. "/custom.js"

local _, vivaldi_install = posix.find("/opt", { name = "vivaldi-bin" })
local _, dir = posix.dirname(vivaldi_install)
dir = dir:gsub("\n", "")
local resources_dir = dir .. "/resources/vivaldi"

print("Patch originating from " .. mod_dir .. " targeting " .. dir)

local backup_files = fs.glob(resources_dir .. "/window.html.bak")

if #backup_files == 0 then
    print("Not patched; backing up window.html to window.html.bak...")
    posix.cp(resources_dir .. "/window.html", resources_dir .. "/window.html.bak", { sudo = true })

    print("Patching window.html...")
    posix.sed('s/<\\/body>/<script src="custom.js"><\\/script> <\\/body>/', resources_dir .. "/window.html",
        { flags = "-i", sudo = true })
else
    print("window.html has already been patched")
end

print("Combining js files into custom.js...")
local _, js_files = posix.find(mod_dir, { maxdepth = 1, type = "f", name = "*.js" })
posix.touch(custom_js)
for line in string.gmatch(js_files, "[^\r\n]*") do
    if line == '' then
        break
    end
    posix.cat(line, { append_file = custom_js })
end

print("Copying custom.js...")
posix.cp(custom_js, resources_dir .. "/custom.js", { sudo = true, force = true })

posix.rm(custom_js)
