This file is indexed.

/usr/bin/smd-client is in syncmaildir 1.2.6.2-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
#! /usr/bin/env lua5.1
-- 
-- Released under the terms of GPLv3 or at your option any later version.
-- No warranties.
-- Copyright Enrico Tassi <gares@fettunta.org>

require 'syncmaildir'

-- export syncmaildir to the global namespace
for k,v in pairs(syncmaildir) do _G[k] = v end

-- globals counter for statistics
local statistics = {
	added = 0,
	removed = 0,
	received = 0,
	xdelta = 0,
	files = {},
}

-- ========================= get mail queue =================================
-- queue for fetching mails in blocks of queue_max_len messages
-- to cope with latency

local get_full_email_queue = {}
local queue_max_len = 50

function process_get_full_email_queue()
	local command = {}
	for _,v in ipairs(get_full_email_queue) do
		command[#command+1] = 'GET ' .. v.name
	end
	command[#command+1] = ''
	io.write(table.concat(command,'\n'))
	command = nil
	io.flush()
	local tmp = {}
	for _,v in ipairs(get_full_email_queue) do
		tmp[#tmp+1] = tmp_for(v.name)
		v.tmp = tmp[#tmp]
		statistics.received = statistics.received + receive(io.stdin, tmp[#tmp])
	end
	tmp = nil
	for _,v in ipairs(get_full_email_queue) do
		local hsha_l, bsha_l = sha_file(v.tmp)
		if hsha_l == v.hsha and bsha_l == v.bsha then
			local rc = os.rename(v.tmp, v.name) 
			if rc then
				statistics.added = statistics.added + 1
			else
				log_error('Failed to rename '..v.tmp..' to '..v.name)
				log_error('It may be caused by bad directory permissions, '..
					'please check.')
				os.remove(v.tmp)
				return (trace(false)) -- fail rename tmpfile to actual name
			end
		else
			log_error('The server sent a different email for '..v.name)
			log_error('This problem should be transient, please retry.')
			os.remove(v.tmp)
			return (trace(false)) -- get full email failed, received wrong mail
		end
	end
	get_full_email_queue = {}
	return (trace(true)) -- get full email OK
end

function process_pending_queue()
	local rc = process_get_full_email_queue()
	if not rc then
		io.write('ABORT\n')
		io.flush()
		os.exit(1)
	end
end

-- the function to fetch a mail message
function get_full_email(name,hsha,bsha)
	if dry_run() then
		statistics.added = statistics.added + 1
		statistics.files[#statistics.files + 1] = name 
		return true
	end
	get_full_email_queue[#get_full_email_queue+1] = {
		name = name;
		hsha = hsha;
		bsha = bsha;
	}
	return true
end

-- ======================== header replacing =================================

function merge_mail(header,body,target)
	local h = io.open(header,"r")
	local b = io.open(body,"r")
	local t = io.open(target,"w")
	local l
	while true do
		l = h:read("*l")
		if l and l ~= "" then t:write(l,'\n') else break end
	end
	while true do
		l = b:read("*l")
		if not l or l == "" then break end
	end
	t:write('\n')
	while true do
		l = b:read("*l")
		if l then t:write(l,'\n') else break end
	end
	h:close()
	b:close()
	t:close()
end

function get_header_and_merge(name,hsha)
	local tmpfile = tmp_for(name)
	io.write('GETHEADER '..name..'\n')
	io.flush()
	receive(io.stdin, tmpfile)
	local hsha_l, _ = sha_file(tmpfile)
	if hsha_l == hsha then
		if not dry_run() then
			local tmpfile1 = tmp_for(name)
			merge_mail(tmpfile,name,tmpfile1)
			os.remove(tmpfile)
			os.rename(tmpfile1, name)
		else
			-- we delete the new piece without merging (--dry-run)	
			os.remove(tmpfile)
		end
		return (trace(true)) -- get header OK
	else
		os.remove(tmpfile)
		log_error('The server sent a different email header for '..name)
		log_error('This problem should be transient, please retry.')

		log_tags("receive-header","modify-while-update",false,"retry")
		return (trace(false)) -- get header fails, got a different header
	end
end

-- ============================= renaming ====================================

function compute_renamings(actions)
	local copy = {}
	local delete = {}
	local script = {}
	for _, cmd in ipairs(actions) do
		local opcode = parse(cmd, '^(%S+)')
		if opcode == "COPY" then
			local name_src, hsha, bsha, name_tgt = 
				parse(cmd, '^COPY (%S+) (%S+) (%S+) TO (%S+)$')
			name_src = url_decode(name_src)
			name_tgt = url_decode(name_tgt)
			copy[#copy + 1] = { src = name_src, tgt = name_tgt}
		elseif opcode == "DELETE" then
			local name, hsha, bsha = parse(cmd, '^DELETE (%S+) (%S+) (%S+)$')
			name = url_decode(name)
			delete[name] = 1
		elseif opcode == 'ERROR' then
			local msg = parse(cmd, '^ERROR (.*)$')
			execute_error(msg)
			io.write('ABORT\n')
			io.flush()
			os.exit(6)
		end
	end
	for _, cp in ipairs(copy) do
		-- it is a real move
		if delete[cp.src] then
			local absolute1, t1, last1 = tokenize_path(cp.src)
			local absolute2, t2, last2 = tokenize_path(cp.tgt)
			local dir1 = table.concat(t1,'/')
			local dir2 = table.concat(t2,'/')
			if not absolute1 and not absolute2 and 
				last1 ~= nil and last2 ~= nil and
				(t1[#t1] == "cur" or t1[#t1] == "new") and
				(t2[#t2] == "cur" or t2[#t2] == "new") and
				dir1 == dir2 then
				--and is_translator_set() then
				local t_dir =  homefy(translate(dir1))
				if delete[cp.src] > 1 then
					table.insert(script,1,string.format("cp %s %s",
						quote(t_dir..'/'..last1),
						quote(t_dir..'/'..last2)))
				else
					script[#script + 1] = string.format("mv %s %s",
						quote(t_dir..'/'..last1),
						quote(t_dir..'/'..last2))
				end
				delete[cp.src] = delete[cp.src] + 1
			end
		end
	end
	return script
end

-- ============================= actions =====================================

function execute_add(name, hsha, bsha)
	local ex, hsha_l, bsha_l = exists_and_sha(name)
	if ex then
		if hsha == hsha_l and bsha == bsha_l then
			return (trace(true)) -- skipping add since already there
		else
			log_error('Failed to add '..name..
				' since a file with the same name')
			log_error('exists but its content is different.')
			log_error('To fix this problem you should rename '..name)
			log_error('Executing `cd; mv -n '..quote(name)..' '..
				quote(tmp_for(name,false))..'` should work.')

			log_tags("mail-addition","concurrent-mailbox-edit",true,
				mk_act("mv", name))
			return (trace(false)) -- skipping add since already there but !=
		end
	end
	return (get_full_email(name,hsha,bsha))
end

function execute_delete(name, hsha, bsha)
	local ex, hsha_l, bsha_l = exists_and_sha(name)
	if ex then
		if hsha == hsha_l and bsha == bsha_l then
			local rc
			if not dry_run() then
				rc = os.remove(name)
			else
				rc = true -- we do not delete the message for real (--dry-run)
			end
			if rc then
				statistics.removed = statistics.removed + 1
				return (trace(true)) -- removed successfully
			else
				log_error('Deletion of '..name..' failed.')
				log_error('It may be caused by bad directory permissions, '..
					'please check.')

				log_tags("delete-message","bad-directory-permission",true,
					mk_act("permission",name))
				return (trace(false)) -- os.remove failed
			end
		else
			log_error('Failed to delete '..name..
				' since the local copy of it has')
			log_error('modifications.')
			log_error('To fix this problem you have two options:')
			log_error('- delete '..name..' by hand')
			log_error('- run @@INVERSECOMMAND@@ so that this file is added '..
				'to the other mailbox')

			log_tags("delete-message", "concurrent-mailbox-edit",true,
				mk_act('display',name),
				mk_act('rm',name),
				"run(@@INVERSECOMMAND@@ @@ENDPOINT@@)")
			return (trace(false)) -- remove fails since local file is !=
		end
	end
	return (trace(true)) -- already removed
end

function execute_copy(name_src, hsha, bsha, name_tgt)
	local ex_src, hsha_src, bsha_src = exists_and_sha(name_src)
	local ex_tgt, hsha_tgt, bsha_tgt = exists_and_sha(name_tgt)
	if ex_src and ex_tgt then
		if hsha_src == hsha_tgt and bsha_src == bsha_tgt and
		   hsha_src == hsha and bsha_src == bsha then
			return (trace(true)) -- skip copy, already there
		else
			log_error('Failed to copy '..name_src..' to '..name_tgt)
			log_error('The destination already exists but its content differs.')
			log_error('To fix this problem you have two options:')
			log_error('- rename '..name_tgt..' by hand so that '..name_src)
			log_error('  can be copied without replacing it.')
			log_error('  Executing `cd; mv -n '..quote(name_tgt)..' '..
				quote(tmp_for(name_tgt,false))..'` should work.')
			log_error('- run @@INVERSECOMMAND@@ so that your changes to '..
				name_tgt)
			log_error('  are propagated to the other mailbox')

			log_tags("copy-message","concurrent-mailbox-edit",true,
				mk_act('mv',name_tgt),
				"run(@@INVERSECOMMAND@@ @@ENDPOINT@@)")
			return (trace(false)) -- fail copy, already there but !=
		end
	elseif ex_src and not ex_tgt then
		if hsha_src == hsha and bsha_src == bsha then
				local ok, err
				if not dry_run() then
					ok, err = cp(name_src,name_tgt)
				else
					ok = 0 -- we do not copy for real (--dry-run)
				end
				if ok == 0 then
					return (trace(true)) -- copy successful
				else 
					log_error('Failed to copy '..name_src..' to '..name_tgt..
						' : '..(err or 'unknown error'))

					log_tags("delete-message","bad-directory-permission",true,
						mk_act('display', name_tgt))
					return (trace(false)) -- copy failed (cp command failed)
				end
		else
				-- sub-optimal, we may reuse body or header
				return (get_full_email(name_tgt,hsha,bsha))
		end
	elseif not ex_src and ex_tgt then
		if hsha == hsha_tgt and bsha == bsha_tgt then
			return (trace(true)) -- skip copy, already there (only the copy)
		else
			log_error('Failed to copy '..name_src..' to '..name_tgt)
			log_error('The source file has been locally removed.')
			log_error('The destination file already exists but its '..
				'content differs.')
			log_error('To fix this problem you have two options:')
			log_error('- rename '..name_tgt..' by hand so that '..
				name_src..' can be')
			log_error('  copied without replacing it.')
			log_error('  Executing `cd; mv -n '..quote(name_tgt)..' '..
				quote(tmp_for(name_tgt,false))..'` should work.')
			log_error('- run @@INVERSECOMMAND@@ so that your changes to '..
				name_tgt..' are')
			log_error('  propagated to the other mailbox')

			log_tags("copy-message","concurrent-mailbox-edit",true,
				mk_act('mv', name_tgt),
				"run(@@INVERSECOMMAND@@ @@ENDPOINT@@)")
			return (trace(false)) -- skip copy, already there and !=, no source
		end
	else
		return (get_full_email(name_tgt,hsha,bsha))
	end
end

function execute_move(name_src, hsha, bsha, name_tgt)
	local ex_src, hsha_src, bsha_src = exists_and_sha(name_src)
	local ex_tgt, hsha_tgt, bsha_tgt = exists_and_sha(name_tgt)
	if ex_src and ex_tgt then
		if hsha_tgt == hsha and bsha_tgt == bsha then
			-- the target is already in place
			if hsha_src == hsha and bsha_src == bsha then
				return (execute_delete(name_src,hsha,bsha))
			else
				return (trace(true)) -- the source has changes, nothing to do
			end
		else
			log_error('Failed to move '..name_src..' to '..name_tgt)
			log_error('The destination already exists but its content differs.')
			log_error('To fix this problem you have two options:')
			log_error('- rename '..name_tgt..' by hand so that '..name_src)
			log_error('  can be copied without replacing it.')
			log_error('  Executing `cd; mv -n '..quote(name_tgt)..' '..
				quote(tmp_for(name_tgt,false))..'` should work.')
			log_error('- run @@INVERSECOMMAND@@ so that your changes to '..
				name_tgt)
			log_error('  are propagated to the other mailbox')

			log_tags("move-message","concurrent-mailbox-edit",true,
				mk_act('mv',name_tgt),
				"run(@@INVERSECOMMAND@@ @@ENDPOINT@@)")
			return (trace(false)) -- fail move, already there but !=
		end
	elseif ex_src and not ex_tgt then
		if hsha_src == hsha and bsha_src == bsha then
			local ok, err
			if not dry_run() then
				ok, err = os.rename(name_src,name_tgt)
			else
				ok = true -- we do not move for real (--dry-run)
			end
			if ok then
				return (trace(true)) -- move successful
			else
				log_error('Failed to move '..name_src..' to '..name_tgt..
					' : '..(err or 'unknown error'))

				log_tags("move-message","bad-directory-permission",true,
					mk_act('display', name_tgt))
				return (trace(false)) -- copy failed (cp command failed)
			end
		else
			-- sub-optimal, we may reuse body or header
			return (get_full_email(name_tgt,hsha,bsha))
		end
	elseif not ex_src and ex_tgt then
		if hsha == hsha_tgt and bsha == bsha_tgt then
			return (trace(true)) -- skip move, already there (and no source)
		else
			log_error('Failed to move '..name_src..' to '..name_tgt)
			log_error('The source file has been locally removed.')
			log_error('The destination file already exists but its '..
				'content differs.')
			log_error('To fix this problem you have two options:')
			log_error('- rename '..name_tgt..' by hand so that '..
				name_src..' can be')
			log_error('  copied without replacing it.')
			log_error('  Executing `cd; mv -n '..quote(name_tgt)..' '..
				quote(tmp_for(name_tgt,false))..'` should work.')
			log_error('- run @@INVERSECOMMAND@@ so that your changes to '..
				name_tgt..' are')
			log_error('  propagated to the other mailbox')

			log_tags("copy-message","concurrent-mailbox-edit",true,
				mk_act('mv', name_tgt),
				"run(@@INVERSECOMMAND@@ @@ENDPOINT@@)")
			return (trace(false)) -- skip copy, already there and !=, no source
		end
	else
		return (get_full_email(name_tgt,hsha,bsha))
	end
end

function execute_replaceheader(name, hsha, bsha, hsha_new)
	if exists(name) then
		local hsha_l, bsha_l = sha_file(name)
		if hsha == hsha_l and bsha == bsha_l then
			return (get_header_and_merge(name,hsha_new))
		elseif hsha_l == hsha_new and bsha == bsha_l then
			return (trace(true)) -- replace header ok, already changend
		else
			log_error('Failed to replace '..name..' header since it has local')
			log_error(' modifications.')
			log_error('To fix this problem you should rename '..name)
			log_error('Executing `cd; mv -n '..quote(name)..' '..
				quote(tmp_for(name,false))..'` should work.')
			log_tags("header-replacement","concurrent-mailbox-edit",true,
				mk_act('mv', name))
			return (trace(false)) -- replace header fails, local header !=
		end
	else
		return (get_full_email(name,hsha_new,bsha))
	end
end

function execute_copybody(name, bsha, newname, hsha)
	local exn, hsha_ln, bsha_ln = exists_and_sha(newname)
	if not exn then
		local ex, _, bsha_l = exists_and_sha(name)
		if ex and bsha_l == bsha then
			local ok, err
			if not dry_run() then
				ok, err = cp(name,newname)
			else
				ok = 0 -- we do not copy the body for merging (--dry-run)
			end
			if ok == 0 then
				ok = get_header_and_merge(newname,hsha)
				if ok then
					return (trace(true)) -- copybody OK
				else
					os.remove(newname)
					return (trace(false)) -- copybody failed, bad new header
				end
			else 
				log_error('Failed to copy '..name..' to '..newname..' : '..
					(err or 'unknown error'))
					
				log_tags("copy-message","bad-directory-permission",true,
					mk_act('display', newname))
				return (trace(false)) -- copybody failed (cp command failed)
			end
		else
			return(get_full_email(newname,hsha,bsha))
		end
	else
		if bsha == bsha_ln and hsha == hsha_ln then
			return (trace(true)) -- copybody OK (already there)
		else
			log_error('Failed to copy body of '..name..' to '..newname)
			log_error('To fix this problem you should rename '..newname)
			log_error('Executing `cd; mv -n '..quote(newname)..' '..
				quote(tmp_for(newname,false))..'` should work.')

			log_tags("copy-body","concurrent-mailbox-edit",true,
				mk_act('mv', newname))
			return (trace(false)) -- copybody failed (already there, != )
		end
	end
end

function execute_replace(name1, hsha1, bsha1, hsha2, bsha2)
	local exn, hsha_ln, bsha_ln = exists_and_sha(name1)
	if not exn then
		return(get_full_email(name1,hsha2,bsha2))
	else
		if bsha2 == bsha_ln and hsha2 == hsha_ln then
			return (trace(true)) -- replace OK (already there)
		elseif bsha1 == bsha_ln and hsha1 == hsha_ln then
			return(get_full_email(name1,hsha2,bsha2))
		else
			log_error('Failed to replace '..name1)
			log_error('To fix this problem you should rename '..name1)
			log_error('Executing `cd; mv -n '..quote(name1)..' '..
				quote(tmp_for(name1,false))..'` should work.')

			log_tags("replace","concurrent-mailbox-edit",true,
				mk_act('mv', name1))
			return (trace(false)) -- replace failed (already there, != )
		end
	end
end

function execute_error(msg)
	
	log_error('mddiff failed: '..msg)
	if msg:match('^Unable to open directory') then
		log_tags("mddiff","directory-disappeared",false)
	else
		log_tags("mddiff","unknown",true)
	end

	return (trace(false)) -- mddiff error
end

-- the main switch, dispatching actions.
-- extra parentheses around execute_* calls make it a non tail call,
-- thus we get the stack frame print in case of error.
function execute(cmd)
	local opcode = parse(cmd, '^(%S+)')

	if opcode == "ADD" then
		local name, hsha, bsha = parse(cmd, '^ADD (%S+) (%S+) (%S+)$')
		name = url_decode(name)
		mkdir_p(name)
		return (execute_add(name, hsha, bsha))
	end

	if opcode == "DELETE" then
		local name, hsha, bsha = parse(cmd, '^DELETE (%S+) (%S+) (%S+)$')
		name = url_decode(name)
		mkdir_p(name)
		return (execute_delete(name, hsha, bsha))
	end

	if opcode == "COPY" then
		local name_src, hsha, bsha, name_tgt = 
			parse(cmd, '^COPY (%S+) (%S+) (%S+) TO (%S+)$')
		name_src = url_decode(name_src)
		name_tgt = url_decode(name_tgt)
		mkdir_p(name_src)
		mkdir_p(name_tgt)
		return (execute_copy(name_src, hsha, bsha, name_tgt))
	end

	if opcode == "MOVE" then
		local name_src, hsha, bsha, name_tgt =
			parse(cmd, '^MOVE (%S+) (%S+) (%S+) TO (%S+)$')
		name_src = url_decode(name_src)
		name_tgt = url_decode(name_tgt)
		mkdir_p(name_src)
		mkdir_p(name_tgt)
		return (execute_move(name_src, hsha, bsha, name_tgt))
	end
	
	if opcode == "REPLACEHEADER" then
		local name, hsha, bsha, hsha_new = 
			parse(cmd, '^REPLACEHEADER (%S+) (%S+) (%S+) WITH (%S+)$')
		name = url_decode(name)
		mkdir_p(name)
		return (execute_replaceheader(name, hsha, bsha, hsha_new))
	end

	if opcode == "COPYBODY" then
		local name, bsha, newname, hsha = 
			parse(cmd, '^COPYBODY (%S+) (%S+) TO (%S+) (%S+)$')
		name = url_decode(name)
		newname = url_decode(newname)
		mkdir_p(name)
		mkdir_p(newname)
		return (execute_copybody(name, bsha, newname, hsha))
	end

	if opcode == "REPLACE" then
		local name1, hsha1, bsha1, hsha2, bsha2 = 
			parse(cmd, '^REPLACE (%S+) (%S+) (%S+) WITH (%S+) (%S+)$')
		name1 = url_decode(name1)
		mkdir_p(name1)
		return (execute_replace(name1, hsha1, bsha1, hsha2, bsha2))
	end

	if opcode == "ERROR" then
		local msg = parse(cmd, '^ERROR (.*)$')
		return (execute_error(msg))
	end
	
	log_internal_error_and_fail('Unknown opcode '..opcode, "protocol")
end

-- ============================= MAIN =====================================

-- report every n mails
local report_frequency = 5000

-- receive a list of commands
function receive_delta(inf, firsttime)
	local cmds = {}
	local line = ""

	log_progress('Phase 1: changes detection')
	if firsttime then
		log_progress([[
		 This phase computes the SHA1 sum of all the emails in the remote
		 mailbox.
		 Depending on the size of the mailbox size and the speed of the hard
		 drive, this operation may take a lot of time. After the first
		 synchronization it will be much faster, since only new emails have
		 to be scanned.
		 On a cheap laptop it takes 10m to scan a 1G mailbox.]])
	end

	repeat
		line = inf:read("*l")
		if line and line ~= "END" then cmds[#cmds+1] = line end
		if #cmds % report_frequency == 0 and #cmds > 0 then
			log_progress(string.format('  %3dK emails scanned', #cmds / 1000))
		end
	until not line or line == "END"
	if line ~= "END" then
		log_error('Unable to receive a complete diff')
		log_tags_and_fail("network error while receiving delta",
			"receive-delta","network",false,"retry")
	end

	return cmds
end

function main()
	-- sanity checks for external softwares
	assert_exists(MDDIFF)
	assert_exists(XDELTA)

	-- argument parsing
	local usage = "Usage: "..arg[0]:match('[^/]+$')..
		" [-vd] [-t translatorRL] endpointname mailboxes...\n"
	local apply_xdelta = true
	local rename_only = false
	local override_db = nil
	while #arg > 2 do
		if arg[1] == '-v' or arg[1] == '--verbose' then
			set_verbose(true)
			table.remove(arg,1)
		elseif arg[1] == '-d' or arg[1] == '--dry-run' then
			set_dry_run(true)
			table.remove(arg,1)
		elseif arg[1] == '-l' or arg[1] == '--local-sync' then
			apply_xdelta = false
			table.remove(arg,1)
		elseif arg[1] == '-t' or arg[1] == '--translator' then
			set_translator(arg[2])
			table.remove(arg,1)
			table.remove(arg,1)
		elseif arg[1] == '--rename-only' then
			rename_only = true
			table.remove(arg,1)
		elseif arg[1] == '--override-db' then
			override_db = arg[2]
			table.remove(arg,1)
			table.remove(arg,1)
		else
			break
		end
	end
	
	if #arg < 2 then
		io.stderr:write(usage)
		os.exit(2)
	end

	-- here we go
	local endpoint = arg[1]
	table.remove(arg,1)
	local dbfile = nil
	if override_db ~= nil then
		dbfile = override_db:gsub('^~',os.getenv('HOME'))
	else
		dbfile = dbfile_name(endpoint, arg)
	end
	local xdelta = dbfile .. '.xdelta'
	local newdb = dbfile .. '.new'
	
	-- sanity check, translator and absolute paths cannot work
	for _, v in ipairs(arg) do
		if v:byte(1) == string.byte('/',1) then
			log_error("Absolute paths are not supported: "..v)
			log_tags_and_fail("Absolute path detected",
				"main","mailbox-has--absolute-path",true)
		end
	end

	-- we check the protocol version and dbfile fingerprint
	local firsttime = not exists(dbfile)
	if firsttime then
		log_progress('This is the first synchronization, '..
			'verbose progress report enabled.')
	end
	log_progress('Phase 0: handshake')
	if firsttime then log_progress(' This phase opens the ssh connection.') end

	handshake(dbfile)
	
	-- receive and process commands
	local commands = receive_delta(io.stdin, firsttime)
	if rename_only then
			-- in renaming mode, we handle commands in a peculiar way
			log_progress('Phase 2: renaming script generation')
			local script = compute_renamings(commands)
			local fname = os.getenv('HOME')..'/smd-rename.sh'
			local f = io.open(fname,'w')
			f:write('#!/bin/sh\n\n')
			f:write(table.concat(script,'\n'))
			f:close()
			log('Please check and run: '..fname)
			-- and we exit
			os.exit(0)
	end

	log_progress('Phase 2: synchronization')
	if firsttime then
		log_progress([[
		 This phase propagates the chages occurred to the remote mailbox to
		 the local one.
		 In the first run of smd-pull all remote emails are considered as
		 new, and if not already present in the local mailbox, they are
		 transferred over the ssh link.
		 It is thus recommended to run the first synchronization on mailboxes
		 that are resonably similar (i.e. not on an empty local mailbox).]])
	end
	for i,cmd in ipairs(commands) do
		local rc = execute(cmd)
		if not rc then
			io.write('ABORT\n')
			io.flush()
			os.exit(3)
		end
		-- some commands are delayed, we fire them in block
		if #get_full_email_queue > queue_max_len then
				process_pending_queue()
		end
		if firsttime and i % report_frequency == 0 then
			log_progress(string.format('  %3d%% complete', i / #commands * 100))
		end
	end
	-- some commands may still be in the queue, we fire them now
	process_pending_queue()
	
	-- we commit and update the dbfile
	log_progress('Phase 3: agreement')
	if firsttime then
		log_progress([[
		 This last phase concludes the agreement between the remote and the
		 local mailbox. In particular the s $tatus of the mailbox is sent
		 from the remote host and stored locally.
		 The status file size is circa 7M (3M compressed) for a 1G mailbox
		 and it needs to be transferred completely only the first time.]])
	end
	io.write('COMMIT\n')
	io.flush()
	statistics.xdelta = receive(io.stdin, xdelta)

	local rc
	if not dry_run() and apply_xdelta then
		rc = os.execute(XDELTA..' patch '..xdelta..' '..dbfile..' '..newdb)
	else
		rc = 0 -- the xdelta transmitted with --dry-run is dummy
	end
	if rc ~= 0 and rc ~= 256 then
		log_error('Unable to apply delta to dbfile.')
		io.write('ABORT\n')
		io.flush()
		os.exit(4)
	end
	if not dry_run() and apply_xdelta then
		rc = os.rename(newdb,dbfile)
	else
		rc = true -- with --dry-run there is no xdelta affair
	end
	if not rc then
		log_error('Unable to rename '..newdb..' to '..dbfile)
		io.write('ABORT\n')
		io.flush()
		os.exit(5)
	end
	os.remove(xdelta)
	io.write('DONE\n')
	io.flush()

	-- some machine understandable output before quitting
	log_tag('stats::new-mails('..  statistics.added..
		'), del-mails('..statistics.removed..
		'), bytes-received('..statistics.received..
		'), xdelta-received('..statistics.xdelta..
		')')
	if dry_run() and #statistics.files > 0 then
		log_tag('stats::mail-transferred('..
			table.concat(statistics.files,' , ')..')')
	end

	os.exit(0)
end

-- no more global variables
set_strict()

-- parachute for errors
parachute(main, 6)

-- vim:set ts=4: