local function has_ansible_root(path, recursive)
    if not recursive then
        return vim.uv.fs_stat(
            vim.fs.joinpath(vim.fs.dirname(path), 'ansible.cfg')
        )
    end

    return vim.fs.find('ansible.cfg', {
        path = vim.fs.dirname(path),
        upward = true,
        limit = 1
    })[1]
end

local function yaml_filetype(recursive, p2)
    return function (path)
        print(p2)
        if has_ansible_root(path, recursive) then
            return "yaml.ansible"
        else
            return "yaml"
        end
    end
end

vim.filetype.add({
    extension = {
        ['yaml'] = yaml_filetype(false),
        ['yml'] = yaml_filetype(false),
    },
    pattern = {
        [".*/roles/.*/tasks/.*%.ya?ml"] = yaml_filetype(true),
        [".*/roles/.*/handlers/.*%.ya?ml"] = yaml_filetype(true),
        [".*/playbooks/.*%.ya?ml"] = yaml_filetype(true),
    },
})
