if fs.exists('/sync.state') then
    f = fs.open('/sync.state','r')
    state = textutils.unserialize(f.readAll())
    f.close()
    print('State file found')
else
    state = {}
    state.files = {}
    print('No state file found')
end	


local args = { ... }
if #args == 1 then
    base_url = args[1]
elseif state.base_url then
    base_url = state.base_url
    print('Using base url:')
    print(base_url)
else
	print([[Usage: sync [base_url]
The base_url is saved on a successful
run and will be reused if not given at
the command line on next runs.]])
	return
end


index_url = base_url..'index'
--print(index_url)
serialized_data = http.get(index_url).readAll()
--print(serialized_data)
index = textutils.unserialize(serialized_data)
--print(index)
state.base_url = base_url


-- Create dirs
for i=1,#index.dirs do
    dir = index.dirs[i]
    if fs.exists(dir) then
        if not fs.isDir(dir) then
            print('Warning, "'..dir..'" is not a dir...')
        end
    else
        fs.makeDir(dir)
    end
end

-- Download and create files if ts larger then stored ts
up_to_date = true
for fn,ts in pairs(index.files) do
    --print(fn)
    --print(ts)
    if state.files[fn] and state.files[fn] >= ts then
        -- print('Skipping "'..fn..'"')
    else
        data = http.get(base_url..fn).readAll()
        f = fs.open(fn, 'w')
        f.write(data)
        f.close()
        state.files[fn] = ts
        up_to_date = false
        print('Updated "'..fn..'"')
    end
end

if up_to_date then
    print('All files were up-to-date...')
end

f = fs.open('/sync.state','w')
f.write(textutils.serialize(state))
f.close()

