# SPDX-FileCopyrightText: Stone Tickle <lattis@mochiro.moe>
# SPDX-License-Identifier: GPL-3.0-only

fs = import('fs')

posargc = 5

if argv.length() < posargc + 1
    error(
        'usage: @0@ <src> <dest> <pat> <fallback> <source root> [cmd]'.format(
            argv[0],
        ),
    )
endif

src = argv[1]
dest = argv[2]
sep = argv[3]
fallback = argv[4]
source_root = argv[5]

i = -1
cmd = []
args = []
foreach e : argv
    i += 1

    if i <= posargc
        continue
    elif i == posargc + 1
        cmd = [e]
    else
        args += [e]
    endif
endforeach

found_tag = false

if cmd.length() == 1
    programs = [[cmd[0], args]]
else
    programs = [['git', ['-C', source_root, 'describe', '--dirty=+']]]
endif

foreach p : programs
    prog = find_program(p[0], required: false)

    if not prog.found()
        continue
    endif

    runres = run_command(prog, p[1], check: false)
    if runres.returncode() != 0
        continue
    endif

    found_tag = true
    vcs_tag = runres.stdout().strip()
endforeach

if not found_tag
    vcs_tag = fallback
endif

s = fs.read(src)
fs.write(dest, vcs_tag.join(s.split(sep)))
