-- This function merges the Packages folder from a DevModule into a shared
-- location. Until we have an improved package implementation, we need to
-- manually dedupe our libraries to cut down on bloat

local function dedupePackages(packages: Folder)
    local packageStorage = getPackageStorage()

    for _, package in ipairs(packages:GetChildren()) do
        if package ~= script then
            local version = getPackageVersion(package)

            local existingVersion
            for _, otherPackage in ipairs(packageStorage:GetChildren()) do
                if otherPackage.Name:match(("^%s_"):format(package.Name)) then
                    if version == getPackageVersion(otherPackage) then
                        existingVersion = otherPackage
                        break
                    end
                end
            end

            if not existingVersion then
                local clone = package:Clone()
                clone.Parent = packageStorage
                clone.Name = ("%s_%s"):format(clone.Name, version)
                existingVersion = clone
            end

            -- Link the package with the existing version (which was either
            -- there previously, or is the one we just generated)
            local packageRef = script.PackageRef:Clone()
            packageRef.Name = package.Name
            packageRef.Package.Value = existingVersion
            packageRef.Parent = package.Parent

            package:Destroy()

            log("link", ('%s <-> %s'):format(package.Name, existingVersion:GetFullName()))
        end
    end
end
