File: git-ftp

package info (click to toggle)
git-ftp 1.5.1+dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 272 kB
  • sloc: sh: 2,545; makefile: 76
file content (1724 lines) | stat: -rwxr-xr-x 46,953 bytes parent folder | download
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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
#!/usr/bin/env bash
#
# Copyright 2010-2015 René Moser
# http://github.com/git-ftp/git-ftp
#
# Git-ftp is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Git-ftp is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Git-ftp.  If not, see <http://www.gnu.org/licenses/>.

# ------------------------------------------------------------
# Setup Environment
# ------------------------------------------------------------

# General config
readonly DEFAULT_PROTOCOL="ftp"
readonly REMOTE_LCK_FILE="$(basename "$0").lck"
readonly SYSTEM="$(uname)"
readonly VERSION='1.5.1'

# ------------------------------------------------------------
# Defaults
# ------------------------------------------------------------
URL=""
REMOTE_PROTOCOL=""
REMOTE_HOST=""
REMOTE_USER=""
REMOTE_PASSWD=""
REMOTE_BASE_URL=""
REMOTE_BASE_URL_DISPLAY=""
REMOTE_ROOT=""
REMOTE_PATH=""
REMOTE_CACERT=""
REMOTE_DELETE_CMD="-*DELE "
REMOTE_CMD_OPTIONS=("-s")
LFTP_OPTIONS=""
ACTION=""
LOG_CACHE=""
ERROR_LOG=""
BRANCH=""
CURRENT_BRANCH=""
SCOPE=""
KEYCHAIN_USER=""
KEYCHAIN_HOST=""
DEPLOYED_SHA1_FILE=".git-ftp.log"
DEPLOYED_SHA1=""
PREV_DEPLOYED_SHA1=""
LOCAL_SHA1=""
SYNCROOT=""
SNAPSHOT_DIR=""
CURL_PROTOCOL=""
CURL_INSECURE="0"
CURL_PUBLIC_KEY=""
CURL_PRIVATE_KEY=""
CURL_DISABLE_EPSV=0
CURL_PROXY=""
TMP_DIR=""
TMP_CURL_UPLOAD_FILE=""
TMP_CURL_DELETE_FILE=""
TMP_GITFTP_UPLOAD=""
TMP_GITFTP_DELETE=""
TMP_GITFTP_INCLUDE=""
declare -a CURL_ARGS
declare -i VERBOSE=0
declare -i IGNORE_DEPLOYED=0
declare -i DOWNLOAD_CHANGED_ONLY=0
declare -i DRY_RUN=0
declare -i FORCE=0
declare -i ENABLE_REMOTE_LCK=0
declare -i ACTIVE_MODE=0
declare -i USE_KEYCHAIN=0
declare -i EXECUTE_HOOKS=1
declare -i ENABLE_POST_HOOK_ERRORS=0
declare -a GIT_SUBMODULES
declare -i AUTO_INIT=0

# ------------------------------------------------------------
# Constant Exit Error Codes
# ------------------------------------------------------------
readonly ERROR_USAGE=2
readonly ERROR_MISSING_ARGUMENTS=3
readonly ERROR_UPLOAD=4
readonly ERROR_DOWNLOAD=5
readonly ERROR_UNKNOWN_PROTOCOL=6
readonly ERROR_REMOTE_LOCKED=7
readonly ERROR_GIT=8
readonly ERROR_HOOK=9
readonly ERROR_FILESYSTEM=10

# ------------------------------------------------------------
# Functions
# ------------------------------------------------------------

usage_long()
{
local pager=$(git config --get core.pager)
${GIT_PAGER:-${pager:-${PAGER:-less -FRSX}}} << EOF
USAGE
	git-ftp <action> [<options>] [<url>]


DESCRIPTION
	git-ftp does FTP the Git way.

	It uses Git to determine which local files have changed since the last
	deployment to the remote server and saves you time and bandwidth by
	uploading only those files.

	It keeps track of the deployed state by uploading the SHA1 of the last
	deployed commit in a log file.

ACTIONS
	. init
		Does an initial upload of the latest version of all non-ignored
		git-tracked files to the remote server and creates .git-ftp.log
		file containing the SHA1 of the latest commit.

	. catchup
		Updates the commit id stored on the server.

	. push
		Uploads git-tracked files which have changed since last upload.

	. download (EXPERIMENTAL)
		Downloads changes from the remote host into your working tree.
		WARNING: It can delete local untracked files that are not
		listed in your .git-ftp-ignore file.

	. pull (EXPERIMENTAL)
		Downloads changes from the remote server into a separate commit
		and merges them into your current branch.

	. snapshot (EXPERIMENTAL)
		Downloads files into a new Git repository. Takes an additional
		optional argument as local destination directory. Example:
		\`git-ftp snapshot ftp://example.com/public_html projects/example\`

	. show
		Downloads last uploaded SHA1 from log and hooks \`git show\`.

	. log
		Downloads last uploaded SHA1 from log and hooks \`git log\`.

	. add-scope
		Add a scope (e.g. dev, production, testing).

	. remove-scope
		Completely remove a scope.

	. help
		Shows this help screen.


URL
	. FTP (default)		host.example.com[:<port>][/<remote path>]
	. FTP			ftp://host.example.com[:<port>][/<remote path>]
	. SFTP			sftp://host.example.com[:<port>][/<remote path>]
	. FTPS			ftps://host.example.com[:<port>][/<remote path>]
	. FTPES			ftpes://host.example.com[:<port>][/<remote path>]


OPTIONS
	-h, --help		Shows this help screen.
	-u, --user		FTP login name.
	-p, --passwd		FTP password.
	-P, --ask-passwd	Ask for FTP password interactively.
	-k, --keychain		FTP password from KeyChain (Mac OS X only).
	-b, --branch		Git branch to push
	-s, --scope		Using a scope (e.g. dev, production, testing).
	-D, --dry-run		Dry run: Does not upload anything.
	-a, --all		Uploads all files, ignores deployed SHA1 hash.
	-c, --commit		Sets SHA1 hash of last deployed commit by option.
	-A, --active		Use FTP active mode.
	-l, --lock		Enable/Disable remote locking.
	-f, --force		Force, does not ask questions.
	-n, --silent		Silent mode.
	-v, --verbose		Verbose mode.
	-vv			Very verbose or debug mode.
	--remote-root		Specifies remote root directory
	--syncroot		Specifies a local directory to sync from as if it were the git project root path.
	--key			SSH private key file name for SFTP.
	--pubkey		SSH public key file name. Used with --key option.
	--insecure		Don't verify server's certificate.
	--cacert		Specify a <file> as CA certificate store. Useful when a server has got a self-signed certificate.
	--no-commit		Perform the merge at the and of pull but do not autocommit, to have the chance to inspect and further tweak the merge result before committing.
	--changed-only		Download or pull only files changed since the deployed commit while ignoring all other files.
	--no-verify		Bypass the pre-ftp-push hook.
	--enable-post-errors	Fails if post-ftp-push hook raises an error
	--disable-epsv		Tell curl to disable the use of the EPSV command when doing passive FTP transfers. Curl will normally always first attempt to use EPSV before PASV, but with this option, it will not try using EPSV.
	--auto-init		Automatically run init action when running push action
	--version		Prints version.
	-x, --proxy		Use the specified proxy.


EXAMPLES
	. git-ftp push -u john ftp://ftp.example.com:4445/public_ftp -p -v
	. git-ftp push -p -u john -v ftp.example.com:4445:/public_ftp
	. git-ftp push -p -u john ftp.example.com --branch prod
	. git-ftp add-scope production ftp://user:secr3t@ftp.example.com:4445/public_ftp
	. git-ftp push --scope production
	. git-ftp remove-scope production


SET DEFAULTS
	. git config git-ftp.user john
	. git config git-ftp.url ftp.example.com
	. git config git-ftp.password secr3t
	. git config git-ftp.remote-root "~/www/"
	. git config git-ftp.branch prod
	. git config git-ftp.syncroot path/dir
	. git config git-ftp.cacert path/cacert
	. git config git-ftp.deployedsha1file mySHA1File
	. git config git-ftp.insecure 1
	. git config git-ftp.keychain user@example.com


SET SCOPE DEFAULTS
	e.g. your scope is 'testing'
	. git config git-ftp.testing.url ftp.example.local


VERSION
	$VERSION
EOF
exit 0
}

usage() {
	echo "git-ftp <action> [<options>] [<url>]"
	exit "$ERROR_USAGE"
}

cache_git_submodules() {
	GIT_SUBMODULES="$(git submodule status -- "$SYNCROOT" 2>/dev/null | grep -v '^-' | awk '{print $2}')"
}

is_submodule() {
	echo "${GIT_SUBMODULES[@]}" | grep -Fxq -- "$1"
}

ask_for_passwd() {
	echo -n "Password: "
	stty -echo > /dev/null 2>&1
	read REMOTE_PASSWD
	stty echo > /dev/null 2>&1
	echo ""
}

get_keychain_password () {
	if [ "$SYSTEM" = "Darwin" ]; then
		# Split user and host if necessary
		if echo "$KEYCHAIN_USER" | grep -q '@'; then
			KEYCHAIN_HOST=$(echo "$KEYCHAIN_USER" | cut -d '@' -f2)
			KEYCHAIN_USER=$(echo "$KEYCHAIN_USER" | cut -d '@' -f1)
		else
			[ -z "$KEYCHAIN_USER" ] && KEYCHAIN_USER="$REMOTE_USER"
			[ -z "$KEYCHAIN_HOST" ] && KEYCHAIN_HOST="$REMOTE_HOST"
		fi

		[ -z "$KEYCHAIN_USER" ] && print_error_and_die "Missing keychain account." "$ERROR_MISSING_ARGUMENTS"
		CURL_ARGS=(-a "$KEYCHAIN_USER")
		[ -n "$KEYCHAIN_HOST" ] && CURL_ARGS+=(-s "$KEYCHAIN_HOST")

		local pass
		if pass="$(security find-internet-password "${CURL_ARGS[@]}" -g 2>&1 > /dev/null)"; then
			without_prefix="${pass#password: \"}"
			REMOTE_PASSWD="${without_prefix%\"}"
		else
			print_error_and_die "Password not found in keychain for account '$KEYCHAIN_USER @ $KEYCHAIN_HOST'." "$ERROR_MISSING_ARGUMENTS"
		fi
	else
		write_log "Ignoring -k on non-Darwin systems."
	fi
}

# Checks if last command was successful
check_exit_status() {
	if [ $? -ne 0 ]; then
		print_error_and_die "$1, exiting..." "$2"
	fi
}

get_config() {
	# try .git-ftp-config
	[ -n "$SCOPE" ] && [ -f '.git-ftp-config' ] && OUT="$(git config -f '.git-ftp-config' --get "git-ftp.$SCOPE.$1")"
	if [ $? -eq 0 ];
	then
		echo "$OUT"
		return 0
	fi
	[ -f '.git-ftp-config' ] && OUT="$(git config -f '.git-ftp-config' --get "git-ftp.$1")"
	if [ $? -eq 0 ];
	then
		echo "$OUT"
		return 0
	fi
	[ -n "$SCOPE" ] && OUT="$(git config --get "git-ftp.$SCOPE.$1")"
	if [ $? -eq 0 ];
	then
		echo "$OUT"
		return 0
	fi
	OUT="$(git config --get "git-ftp.$1")"
	if [ $? -eq 0 ];
	then
		echo "$OUT"
		return 0
	fi
	[ -n "$2" ] && OUT="$2"
	echo "$OUT"
}

set_deployed_sha1_file() {
	DEPLOYED_SHA1_FILE="$(get_config deployedsha1file .git-ftp.log)"
}

# Simple log func
write_log() {
	if [ $VERBOSE -eq 1 ]; then
		echo "$(date): $1"
	else
		if [ -n "$LOG_CACHE" ]; then
			LOG_CACHE="$LOG_CACHE\n$(date): $1"
		else
			LOG_CACHE="$(date): $1"
		fi
	fi
}

write_error_log() {
	write_log "$1"
	if [ -n "$ERROR_LOG" ]; then
		ERROR_LOG="$ERROR_LOG\n: $1"
	else
		ERROR_LOG="$1"
	fi
}

print_error_log() {
	if [ -n "$ERROR_LOG" ]; then
		echo "Error log:"
		echo "$ERROR_LOG"
	fi
}

# Simple error printer
print_error_and_die() {
	if [ $VERBOSE -eq 0 ]; then
		echo "fatal: $1" >&2
	else
		write_log "fatal: $1"
	fi
	cleanup
	exit "$2"
}

# Simple info printer
print_info() {
	if [ $VERBOSE -eq 0 ]; then
		echo "$1"
	else
		write_log "$1"
	fi
}

cleanup() {
	rm -rf "$TMP_DIR"
}

set_default_curl_options() {
	OIFS="$IFS"
	IFS=" "
	CURL_ARGS=("${REMOTE_CMD_OPTIONS[@]}")
	IFS="$OIFS"
	CURL_ARGS+=(--globoff)
	if [ -n "$CURL_PROXY" ]; then
		CURL_ARGS+=(--proxy "$CURL_PROXY")
	fi
	if [ -z "$REMOTE_USER" ]; then
		CURL_ARGS+=(--netrc)
	fi
	CURL_ARGS+=(-#)
	if [ $ACTIVE_MODE -eq 1 ]; then
		CURL_ARGS+=(-P "-")
	else
		if [ $CURL_DISABLE_EPSV -eq 1 ]; then
			CURL_ARGS+=(--disable-epsv)
		fi
	fi
}

upload_file() {
	local SRC_FILE="$1"
	local DEST_FILE="$2"
	if [ -z "$DEST_FILE" ]; then
		DEST_FILE="${SRC_FILE#$SYNCROOT}"
	fi

	set_default_curl_options
	CURL_ARGS+=(-T "$SRC_FILE")
	CURL_ARGS+=(--ftp-create-dirs)
	CURL_ARGS+=("$REMOTE_BASE_URL/${REMOTE_PATH}${DEST_FILE}")
	curl "${CURL_ARGS[@]}"
	check_exit_status "Could not upload file: '${REMOTE_PATH}$DEST_FILE'." "$ERROR_UPLOAD"
}

upload_file_buffered() {
	local SRC_FILE="$1"
	local DEST_FILE="${SRC_FILE#$SYNCROOT}"
	local ENC_DEST_FILE="${DEST_FILE//#/%23}"
	echo "-T \"./$SRC_FILE\"
url = \"$REMOTE_BASE_URL/${REMOTE_PATH}${ENC_DEST_FILE}\"" >> "$TMP_CURL_UPLOAD_FILE"
}

fire_upload_buffer() {
	if [ ! -f "$TMP_CURL_UPLOAD_FILE" ]; then
		return 0
	fi
	print_info "Uploading ..."
	set_default_curl_options
	CURL_ARGS+=(--ftp-create-dirs)
	CURL_ARGS+=(-K "$TMP_CURL_UPLOAD_FILE")
	curl "${CURL_ARGS[@]}"
	check_exit_status "Could not upload files." "$ERROR_UPLOAD"
}

delete_file() {
	local FILENAME="$1"
	set_default_curl_options
	CURL_ARGS+=(-Q "${REMOTE_DELETE_CMD}${REMOTE_PATH}${FILENAME}")
	CURL_ARGS+=("$REMOTE_BASE_URL")
	if [ "${REMOTE_CMD_OPTIONS[0]}" = "-v" ]; then
		curl "${CURL_ARGS[@]}"
	else
		curl "${CURL_ARGS[@]}" > /dev/null 2>&1
	fi
	if [ $? -ne 0 ]; then
		write_log "WARNING: Could not delete ${REMOTE_PATH}${FILENAME}, continuing..."
	fi
}

delete_file_buffered() {
	echo "-Q \"${REMOTE_DELETE_CMD}${REMOTE_PATH}${1}\"" >> "$TMP_CURL_DELETE_FILE"
}

fire_delete_buffer() {
	if [ ! -f "$TMP_CURL_DELETE_FILE" ]; then
		return 0
	fi
	print_info "Deleting ..."
	echo "url = $REMOTE_BASE_URL" >> "$TMP_CURL_DELETE_FILE"
	set_default_curl_options
	CURL_ARGS+=(-K "$TMP_CURL_DELETE_FILE")
	if [ "${REMOTE_CMD_OPTIONS[0]}" = "-v" ]; then
		curl "${CURL_ARGS[@]}"
	else
		curl "${CURL_ARGS[@]}" > /dev/null 2>&1
	fi
	if [ $? -ne 0 ]; then
		write_log "WARNING: Some files and/or directories could not be deleted."
	fi
}

get_file_content() {
	local SRC_FILE="$1"
	set_default_curl_options
	CURL_ARGS+=("$REMOTE_BASE_URL/${REMOTE_PATH}${SRC_FILE}")
	curl "${CURL_ARGS[@]}"
}

set_local_sha1() {
	LOCAL_SHA1=$(git log -n 1 --pretty=format:%H)
}

upload_local_sha1() {
	write_log "Uploading commit log to $REMOTE_BASE_URL_DISPLAY/${REMOTE_PATH}$DEPLOYED_SHA1_FILE."
	if [ $DRY_RUN -ne 1 ]; then
		echo "$LOCAL_SHA1" | upload_file - "$DEPLOYED_SHA1_FILE"
		check_exit_status "Could not upload." "$ERROR_UPLOAD"
	fi
	print_info "Last deployment changed from $DEPLOYED_SHA1 to $LOCAL_SHA1.";
	PREV_DEPLOYED_SHA1="$DEPLOYED_SHA1"
	DEPLOYED_SHA1="$LOCAL_SHA1"
}

pre_push_hook() {
	local hook='.git/hooks/pre-ftp-push'
	if [ "$EXECUTE_HOOKS" -eq 1 -a -e "$hook" ]; then
		local scope="${SCOPE:-$REMOTE_HOST}"
		local url="$REMOTE_BASE_URL_DISPLAY/$REMOTE_PATH"
		write_log "Trigger pre-ftp-push hook with: $scope, $url, $LOCAL_SHA1, $DEPLOYED_SHA1"
		print_status | $hook "$scope" "$url" "$LOCAL_SHA1" "$DEPLOYED_SHA1" || exit "$ERROR_HOOK"
	fi
}

post_push_hook() {
	local hook='.git/hooks/post-ftp-push'
	if [ -e "$hook" ]; then
		local scope="${SCOPE:-$REMOTE_HOST}"
		local url="$REMOTE_BASE_URL_DISPLAY/$REMOTE_PATH"
		write_log "Trigger post-ftp-push hook with: $scope, $url, $LOCAL_SHA1, $PREV_DEPLOYED_SHA1"
		$hook "$scope" "$url" "$LOCAL_SHA1" "$PREV_DEPLOYED_SHA1" || [ "$ENABLE_POST_HOOK_ERRORS" -eq 0 ] || exit "$ERROR_HOOK"
	fi
}

print_status() {
	while IFS= read -r -d '' FILE_NAME; do
		printf 'A %s\0' "$FILE_NAME"
	done < "$TMP_GITFTP_UPLOAD"
	while IFS= read -r -d '' FILE_NAME; do
		printf 'D %s\0' "$FILE_NAME"
	done < "$TMP_GITFTP_DELETE"
}

remote_lock() {
	[ $ENABLE_REMOTE_LCK -ne 1 ] && return
	[ $FORCE -ne 1 ] && check_remote_lock

	local LCK_MESSAGE="${USER}@$(hostname --fqdn) on $(date --utc --rfc-2822)"

	write_log "Remote locking $LCK_MESSAGE."
	if [ $DRY_RUN -ne 1 ]; then
		echo "${LOCAL_SHA1}\n${LCK_MESSAGE}" | upload_file - "$REMOTE_LCK_FILE"
		check_exit_status "Could not upload remote lock file." "$ERROR_UPLOAD"
	fi
}

release_remote_lock() {
	[ $ENABLE_REMOTE_LCK -ne 1 ] && return;
	write_log "Releasing remote lock."
	delete_file "$REMOTE_LCK_FILE"
}

set_remote_host() {
	[ -z "$URL" ] && URL="$(get_config url)"
	REMOTE_HOST=$(expr "$URL" : ".*://\([[:alpha:]0-9\.:-]*\).*")
	[ -z "$REMOTE_HOST" ] && REMOTE_HOST=$(expr "$URL" : "\([[:alpha:]0-9\.:-]*\).*")
	[ -z "$REMOTE_HOST" ] && print_error_and_die "Remote host not set." "$ERROR_MISSING_ARGUMENTS"
}

set_remote_protocol() {
	# Split protocol from url
	REMOTE_PROTOCOL="$(get_protocol_of_url "$URL")"
	CURL_PROTOCOL="$REMOTE_PROTOCOL"

	# Protocol found?
	if [ ! -z "$REMOTE_PROTOCOL" ]; then
		REMOTE_PATH=$(echo "$URL" | cut -d '/' -f 4-)
		handle_remote_protocol_options
		return
	fi

	# Check if a unknown protocol is set, handle it or use default protocol
	local UNKNOWN_PROTOCOL=$(expr "$URL" : "\(.*:[/]*\).*")
	if [ -z "$UNKNOWN_PROTOCOL" ]; then
		write_log "Protocol not set, using default protocol $DEFAULT_PROTOCOL://."
		REMOTE_PROTOCOL="$DEFAULT_PROTOCOL"
		CURL_PROTOCOL="$REMOTE_PROTOCOL"
		echo "$URL" | egrep -q "/" && REMOTE_PATH=$(echo "$URL" | cut -d '/' -f 2-)
		handle_remote_protocol_options
		return
	fi
	print_error_and_die "Protocol unknown '$UNKNOWN_PROTOCOL'." "$ERROR_UNKNOWN_PROTOCOL"
}

set_remote_path() {
	# Check remote root directory
	[ -z "$REMOTE_ROOT" ] && REMOTE_ROOT="$(get_config remote-root)"
	if [ ! -z "$REMOTE_ROOT" ]; then
		! echo "$REMOTE_ROOT" | egrep -q "/$" && REMOTE_ROOT="$REMOTE_ROOT/"
		REMOTE_PATH="$REMOTE_ROOT$REMOTE_PATH"
	fi

	# Add trailing slash if missing
	if [ ! -z "$REMOTE_PATH" ] && ! echo "$REMOTE_PATH" | egrep -q "/$"; then
		write_log "Added missing trailing / in path."
		REMOTE_PATH="$REMOTE_PATH/"
	fi
}

set_deployed_sha1_failable() {
	# Return if commit is set by user interaction using --commit
	if [ -n "$DEPLOYED_SHA1" ]; then
		return
	fi
	# Get the last commit (SHA) we deployed if not ignored or not found
	write_log "Retrieving last commit from $REMOTE_BASE_URL_DISPLAY/$REMOTE_PATH."
	DEPLOYED_SHA1="$(get_file_content "$DEPLOYED_SHA1_FILE")"
}

set_deployed_sha1() {
	set_deployed_sha1_failable
	check_exit_status "Could not get last commit. Network down? Wrong URL? Use 'git ftp init' for the initial push." "$ERROR_DOWNLOAD"
	write_log "Last deployed SHA1 for $REMOTE_HOST/$REMOTE_PATH is $DEPLOYED_SHA1."
}

set_deployed_sha1_for_push() {
	if [ "$AUTO_INIT" = 1 ]; then
		set_deployed_sha1_failable
		if [ "$DEPLOYED_SHA1" = "" ]; then
			check_remote_access
			write_log "Uploading all files since no commit was found at $REMOTE_BASE_URL_DISPLAY/$REMOTE_PATH."
			IGNORE_DEPLOYED=1
		fi
	else
		set_deployed_sha1
	fi
}

set_changed_files() {
	set_tmp
	# Get raw list of files
	if [ $IGNORE_DEPLOYED -ne 0 ]; then
		write_log "Taking all files.";
		list_all_files
	else
		list_changed_files
	fi
	add_include_files
	filter_ignore_files "$TMP_GITFTP_UPLOAD" "$TMP_GITFTP_DELETE"
	if [ -s "$TMP_GITFTP_UPLOAD" ] || [ -s "$TMP_GITFTP_DELETE" ]; then
		write_log "Having files to sync.";
	else
		write_log "No files to sync. All changed files ignored.";
	fi
}

list_all_files() {
	git ls-files -z -- "${SYNCROOT:-.}" > "$TMP_GITFTP_UPLOAD"
	touch "$TMP_GITFTP_DELETE"
}

list_changed_files() {
	git diff --name-only --no-renames --diff-filter=AM -z "$DEPLOYED_SHA1" -- "$SYNCROOT" 2>/dev/null > "$TMP_GITFTP_UPLOAD"
	git diff --name-only --no-renames --diff-filter=D  -z "$DEPLOYED_SHA1" -- "$SYNCROOT" 2>/dev/null > "$TMP_GITFTP_DELETE"
	local git_diff_status=$?
	if [ "$git_diff_status" -ne 0 ]; then
		if [ $FORCE -eq 1 ]; then
			print_info "Unknown SHA1 object, could not determine changed files, taking all files."
			list_all_files
			return
		fi
		print_info "Unknown SHA1 object, make sure you are deploying the right branch and it is up-to-date."
		echo -n "Do you want to ignore and upload all files again? [y/N]: "
		read ANSWER_STATE
		if [ "$ANSWER_STATE" != "y" ] && [ "$ANSWER_STATE" != "Y" ]; then
			print_info "Aborting..."
			cleanup
			test "$ANSWER_STATE" == "" && exit "$ERROR_USAGE"
			exit 0
		fi
		write_log "Taking all files.";
		list_all_files
	elif [ "$LOCAL_SHA1" == "$DEPLOYED_SHA1" ]; then
		print_info "No changed files for $REMOTE_HOST/$REMOTE_PATH. Everything up-to-date."
		cleanup
		unset_branch
		exit 0
	elif [ ! -s "$TMP_GITFTP_UPLOAD" -a ! -s "$TMP_GITFTP_DELETE" ]; then
		write_log "No changed files, but different commit ID. Changed files ignored or commit amended.";
	fi
}

add_include_files() {
	[ -f '.git-ftp-include' ] || return
	local tmp_include_sources="$TMP_DIR/include_sources_tmp"
	grep -v '^#.*$\|^\s*$' '.git-ftp-include' | tr -d '\r' > "$TMP_GITFTP_INCLUDE"
	grep '^!' "$TMP_GITFTP_INCLUDE" | sed 's/^!//' | while read TARGET; do
		add_include_file "$TARGET"
	done
	local AGAINST="${DEPLOYED_SHA1:-"$(git hash-object -t tree /dev/null)"}"
	grep ':' "$TMP_GITFTP_INCLUDE" | while read LINE; do
		local TARGET="${LINE%%:*}"
		local SOURCE="${LINE#*:}"
		if echo "$SOURCE" | grep -q '^/'; then
			SOURCE="${SOURCE#/}"
		elif [ -n "$SYNCROOT" ]; then
			SOURCE="$SYNCROOT/$SOURCE"
		fi
		if ! git diff --quiet "$AGAINST" -- "$SOURCE"; then
			add_include_file "$TARGET"
		fi
	done
	rm -f "$tmp_include_sources"
	rm -f "$TMP_GITFTP_INCLUDE"
}

add_include_file() {
	local TARGET="${1}"
	if [ -e "$TARGET" ]; then
		if [ -d "$TARGET" ]; then
			write_log "Including all files in $TARGET for upload."
			find "$TARGET" -type f -print0 >> "$TMP_GITFTP_UPLOAD"
		elif [ -f "$TARGET" ]; then
			write_log "Including $TARGET for upload."
			printf '%s\0' "$TARGET" >> "$TMP_GITFTP_UPLOAD"
		fi
	else
		if echo "$TARGET" | grep -v '/$'; then
			write_log "Including $TARGET for deletion."
			printf '%s\0' "$TARGET" >> "$TMP_GITFTP_DELETE"
		else
			write_log "Deletion of directory $TARGET is not supported."
		fi
	fi
}

filter_ignore_files() {
	[ -f '.git-ftp-ignore' ] || return
	local patterns="$TMP_DIR/ignore_tmp"
	grep -v '^#.*$\|^\s*$' '.git-ftp-ignore' | tr -d '\r' > "$patterns"
	filter_file "$patterns" "$1"
	filter_file "$patterns" "$2"
	rm -f "$patterns"
}

filter_file() {
	glob_filter "$1" < "$2" > "$TMP_DIR/filtered_tmp"
	mv "$TMP_DIR/filtered_tmp" "$2"
}

# Original implementation http://stackoverflow.com/a/27718468/3377535
glob_filter() {
	local patterns="$1"
	while IFS= read -r -d '' filename; do
		local hasmatch=0
		while IFS= read -r pattern; do
			case $filename in ($pattern) hasmatch=1; break ;; esac
		done < "$patterns"
		test $hasmatch = 1 || printf '%s\0' "$filename"
	done
}

handle_file_sync() {
	if [ ! -s "$TMP_GITFTP_UPLOAD" ] && [ ! -s "$TMP_GITFTP_DELETE" ]; then
		print_info "There are no files to sync."
		return
	fi
	sort -z -u -o "$TMP_GITFTP_UPLOAD" "$TMP_GITFTP_UPLOAD"
	sort -z -u -o "$TMP_GITFTP_DELETE" "$TMP_GITFTP_DELETE"
	# Calculate total file count
	local DONE_ITEMS=0
	local TOTAL_ITEMS=$(cat "$TMP_GITFTP_UPLOAD" "$TMP_GITFTP_DELETE" | tr -d -c '\0' | wc -c)
	TOTAL_ITEMS=$((TOTAL_ITEMS+0)) # trims whitespaces produced by wc
	print_info "$TOTAL_ITEMS file$([ $TOTAL_ITEMS -ne 1 ] && echo 's') to sync:"

	while IFS= read -r -d '' FILE_NAME; do
		(( DONE_ITEMS++ ))
		print_info "[$DONE_ITEMS of $TOTAL_ITEMS] Buffered for upload '$FILE_NAME'."
		if is_submodule "$FILE_NAME"; then
			handle_submodule_sync "${FILE_NAME#$SYNCROOT}"
		elif [ $DRY_RUN -ne 1 ]; then
			upload_file_buffered "$FILE_NAME"
		fi
	done < "$TMP_GITFTP_UPLOAD"
	fire_upload_buffer

	while IFS= read -r -d '' FILE_NAME; do
		(( DONE_ITEMS++ ))
		print_info "[$DONE_ITEMS of $TOTAL_ITEMS] Buffered for delete '$FILE_NAME'."
		if [ $DRY_RUN -ne 1 ]; then
			local file="${FILE_NAME#$SYNCROOT}"
			delete_file_buffered "$file"
		fi
	done < "$TMP_GITFTP_DELETE"
	fire_delete_buffer
}

handle_submodule_sync() {
	print_info "Handling submodule sync for $1."
	set_submodule_args
	(
		cd "${SYNCROOT}$1" && "$0" "$ACTION" "${args[@]}" "$REMOTE_PROTOCOL://$REMOTE_HOST/${REMOTE_PATH}$1"
	)

	local EXIT_CODE=$?

	# Pushing failed. Submodule may not be initialized
	if [ "$EXIT_CODE" -eq "$ERROR_DOWNLOAD" ] && [ "$ACTION" == "push" ]; then
		print_info "Could not push $1, trying to init..."
		(
			cd "${SYNCROOT}$1" && "$0" init "${args[@]}" "$REMOTE_PROTOCOL://$REMOTE_HOST/${REMOTE_PATH}$1"
		)
		check_exit_status "Failed to sync submodules." "$ERROR_UPLOAD"
	elif [ $EXIT_CODE -ne 0 ]; then
		print_error_and_die "Failed to sync submodules." "$ERROR_UPLOAD"
	fi
}

submodule_catchup() {
	[ -z "$GIT_SUBMODULES" ] && return
	set_submodule_args
	url="$(git config git-ftp.url)"
	print_info "Submodules are $GIT_SUBMODULES"
	for submodule in "${GIT_SUBMODULES[@]}"
	do
		print_info "Catching up submodule $submodule."
		cd "${SYNCROOT}$submodule" && "$0" "$ACTION" "${args[@]}" "$REMOTE_PROTOCOL://$REMOTE_HOST/${REMOTE_PATH}$submodule"
	done
}

set_submodule_args() {
	# Duplicate the current required parameters
	args=(--user "$REMOTE_USER" --passwd "$REMOTE_PASSWD")

	# Do not ask any questions for submodules
	args+=(--force)

	if [ $ACTIVE_MODE -eq 1 ]; then
		args+=(--active)
	else
		if [ $CURL_DISABLE_EPSV -eq 1 ]; then
			args+=(--disable-epsv)
		fi
	fi

	[ $IGNORE_DEPLOYED -eq 1 ] && args+=(--all)

	if [ $VERBOSE -eq 1 ]; then
		args+=(--verbose)
	elif [ $VERBOSE -eq -1 ]; then
		args+=(--silent)
	fi

	[ $DRY_RUN -eq 1 ] && args+=(--dry-run)
}

handle_remote_protocol_options() {
	if [ "$REMOTE_PROTOCOL" = "sftp" ]; then
		set_sftp_config

		if [ -n "$CURL_PRIVATE_KEY" ]; then
			write_log "Using ssh private key file $CURL_PRIVATE_KEY"
			REMOTE_CMD_OPTIONS+=("--key" "$CURL_PRIVATE_KEY")
		fi
		if [ -n "$CURL_PUBLIC_KEY" ]; then
			write_log "Using ssh public key file $CURL_PUBLIC_KEY"
			REMOTE_CMD_OPTIONS+=("--pubkey" "$CURL_PUBLIC_KEY")
		elif [ -f "${CURL_PRIVATE_KEY}.pub" -a -r "${CURL_PRIVATE_KEY}.pub" ]; then
			write_log "Automatically using ssh public key file ${CURL_PRIVATE_KEY}.pub"
			REMOTE_CMD_OPTIONS+=("--pubkey" "${CURL_PRIVATE_KEY}.pub")
		fi

		# SFTP uses a different remove command and uses absolute paths
		REMOTE_DELETE_CMD="rm /"
	fi

	# Check for using cacert
	if [ "$REMOTE_PROTOCOL" = "ftpes" -o "$REMOTE_PROTOCOL" = "ftps" ] && \
	[ -n "$REMOTE_CACERT" -a -r "$REMOTE_CACERT" ]; then
		REMOTE_CMD_OPTIONS+=("--cacert" "$REMOTE_CACERT")
	fi

	# Options for curl if using FTPES
	if [ "$REMOTE_PROTOCOL" = "ftpes" ]; then
		CURL_PROTOCOL="ftp"
		REMOTE_CMD_OPTIONS+=("--ssl")
	fi

	# Require users' explicit consent for insecure connections
	[ "$CURL_INSECURE" != "0" ] && REMOTE_CMD_OPTIONS+=("-k")
}

init_new_repository() {
	[ -z "$URL" ] && print_error_and_die "Error: give a URL to snapshot." "$ERROR_USAGE"

	# Use the last part of the URL as destination directory by default
	[ -z "$SNAPSHOT_DIR" ] && SNAPSHOT_DIR="$(basename "$URL")"

	DEPLOYED_SHA1="$(get_file_content "$DEPLOYED_SHA1_FILE")"
	if [ "$DEPLOYED_SHA1" != "" ]; then
		print_error_and_die "Commit found at $URL/$DEPLOYED_SHA1_FILE.

The remote directory is managed by another Git repository already. If you want
to start using a new repository, then delete $DEPLOYED_SHA1_FILE first. The old
repository will not be able to deploy to this remote any more. Aborting." "$ERROR_USAGE"
	fi

	# Make sure the destination directory exists
	mkdir -p "$SNAPSHOT_DIR" || print_error_and_die "Error creating directory '$SNAPSHOT_DIR'. Aborting." "$ERROR_FILESYSTEM"

	if [ "$(ls -A "$SNAPSHOT_DIR")" ]; then
		print_error_and_die "Error: The destination directory '$SNAPSHOT_DIR' is not empty. Aborting." "$ERROR_FILESYSTEM"
	fi

	cd "$SNAPSHOT_DIR" || print_error_and_die "Error entering '$SNAPSHOT_DIR'. Aborting." "$ERROR_FILESYSTEM"
	info="$(git init)" || print_error_and_die "Error initialising Git repository." "$ERROR_GIT"
	print_info "$info"
}

commit_snapshot() {
	git add . > /dev/null || print_error_and_die "Git: error adding changed files" "$ERROR_GIT"
	git commit -m "Download $URL with git-ftp" -q  > /dev/null || print_error_and_die "Git: error committing the changes" "$ERROR_GIT"
}

handle_action() {
	case "$ACTION" in
		init)
			action_init
			;;
		push)
			action_push
			;;
		catchup)
			action_catchup
			;;
		show)
			action_show
			;;
		log)
			action_log
			;;
		download)
			action_download
			;;
		pull)
			action_pull
			;;
		snapshot)
			action_snapshot
			;;
		add-scope)
			action_add_scope
			;;
		remove-scope)
			action_remove_scope
			;;
		*)
			print_error_and_die "Action unknown." "$ERROR_MISSING_ARGUMENTS"
			;;
	esac
}

set_remote_user() {
	[ -z $REMOTE_USER ] && REMOTE_USER="$(get_config user)"
}

set_remote_cacert() {
	[ -z $REMOTE_CACERT ] && REMOTE_CACERT="$(get_config cacert)"
}

set_remote_password() {
	KEYCHAIN_USER="$(get_config keychain)"
	[ -z "$KEYCHAIN_USER" ] || USE_KEYCHAIN=1
	[ -z "$REMOTE_PASSWD" ] && [ $USE_KEYCHAIN -eq 1 ] && get_keychain_password "$KEYCHAIN_USER"
	[ -z "$REMOTE_PASSWD" ] && REMOTE_PASSWD="$(get_config password)"
}

set_branch() {
	: "${BRANCH:=$(get_config branch)}"
	if [ -n "$BRANCH" ]; then
		set_current_branch
		write_log "Checkout on branch $BRANCH"
		git checkout "$BRANCH" > /dev/null 2>&1 || print_error_and_die "'$BRANCH' is not a valid branch! Exiting..." "ERROR_GIT"
	fi
}

unset_branch() {
	if [ -n "$CURRENT_BRANCH" ]; then
		write_log "Checkout on branch $CURRENT_BRANCH"
		git checkout "$CURRENT_BRANCH" > /dev/null 2>&1
	fi
}

set_syncroot() {
	[ -z "$SYNCROOT" ] && SYNCROOT="$(get_config syncroot)"
	[ -z "$SYNCROOT" ] && SYNCROOT="."
	if [ "$SYNCROOT" ]; then
		[ -d "$SYNCROOT" ] || print_error_and_die "'$SYNCROOT' is not a directory! Exiting..." "$ERROR_GIT"
		SYNCROOT="$(echo "$SYNCROOT" | sed 's#/*$##')/"
	fi
}

set_sftp_config() {
	[ -z "$CURL_PRIVATE_KEY" ] && CURL_PRIVATE_KEY="$(get_config key)"
	[ -z "$CURL_PUBLIC_KEY" ] && CURL_PUBLIC_KEY="$(get_config pubkey)"
}

set_tmp() {
	if command -v mktemp > /dev/null 2>&1; then
		TMP_DIR="$(mktemp -d -t git-ftp-XXXXXX)"
	else
		TMP_DIR="$(pwd)/.git/git-ftp-tmp"
		mkdir -p "$TMP_DIR"
	fi
	TMP_CURL_UPLOAD_FILE="$TMP_DIR/curl_upload_list"
	TMP_CURL_DELETE_FILE="$TMP_DIR/curl_delete_list"
	TMP_GITFTP_UPLOAD="$TMP_DIR/upload_tmp"
	TMP_GITFTP_DELETE="$TMP_DIR/delete_tmp"
	TMP_GITFTP_INCLUDE="$TMP_DIR/include_tmp"
}

set_remotes() {
	set_remote_host
	write_log "Host is '$REMOTE_HOST'."

	set_remote_user
	write_log "User is '$REMOTE_USER'."

	set_remote_password
	if [ -z "$REMOTE_PASSWD" ]; then
		write_log "No password is set."
	else
		write_log "Password is set."
	fi

	local REMOTE_LOGIN=''
	local DISPLAY_LOGIN=''
	if [ ! -z "$REMOTE_USER" ]; then
		local ENC_USER="$(urlencode "$REMOTE_USER")"
		local ENC_PASSWD="$(urlencode "$REMOTE_PASSWD")"
		REMOTE_LOGIN="$ENC_USER":"$ENC_PASSWD"@
		DISPLAY_LOGIN="$ENC_USER":'***'@
	fi

	set_remote_cacert
	write_log "CACert is '$REMOTE_CACERT'."

	set_curl_insecure
	write_log "Insecure is '$CURL_INSECURE'."

	set_curl_proxy
	write_log "Proxy is '$CURL_PROXY'."

	set_remote_protocol
	set_remote_path
	write_log "Path is '$REMOTE_PATH'."

	REMOTE_BASE_URL="$CURL_PROTOCOL://$REMOTE_LOGIN$REMOTE_HOST"
	REMOTE_BASE_URL_DISPLAY="$REMOTE_PROTOCOL://$DISPLAY_LOGIN$REMOTE_HOST"

	set_syncroot
	write_log "Syncroot is '$SYNCROOT'."

	set_deployed_sha1_file
	write_log "The remote sha1 is saved in file '$DEPLOYED_SHA1_FILE'."
}

# Original implementation http://stackoverflow.com/a/10660730/3377535
urlencode() {
	local string="${1}"
	local strlen=${#string}
	local keepset='[-_.~a-zA-Z0-9]'
	[ $# -gt 1 ] && keepset="${2}"
	local encoded=""
	for (( pos=0 ; pos<strlen ; pos++ )); do
		c=${string:$pos:1}
		case "$c" in
			$keepset ) o="${c}" ;;
			* ) printf -v o '%%%02x' "'$c"
		esac
		encoded+="${o}"
	done
	echo "${encoded}"
}

set_curl_insecure() {
	local config="$(get_config insecure)"
	[ -n "$config" ] && CURL_INSECURE="$config"
}

set_curl_proxy() {
	[ -z "$CURL_PROXY" ] && CURL_PROXY="$(get_config proxy)"
	[ -z "$CURL_PROXY" ] && CURL_PROXY="$(git config --get http.proxy)"
}

get_protocol_of_url() {
	echo "$1" | tr '[:upper:]' '[:lower:]' | egrep '^(ftp|sftp|ftps|ftpes)://' | cut -d ':' -f 1
}

download_remote_updates () {
	write_log "Mirroring ${REMOTE_HOST}/${REMOTE_PATH}"
	local mirror_options=''
	if [ "$DRY_RUN" = 1 ]; then
		mirror_options="$mirror_options --dry-run"
	fi
	if [ "$VERBOSE" -gt 0 ]; then
		mirror_options="$mirror_options -v"
	fi

	delete="--delete"
	include=""
	ignoreall=""
	# Mirror only the files from the diff between the FTP commit and the current branch/commit
	if [ "$DOWNLOAD_CHANGED_ONLY" -eq 1 ] && [ -n "$CURRENT_BRANCH" ]; then
		delete=""
		ignoreall=" --exclude '.*' --exclude '.*/'"
		include="$(git diff "$CURRENT_BRANCH" --name-only | sed 's/^\(.*\)$/ --include "\1"/' | tr -d '\r\n')"
		filenames="$(git diff $CURRENT_BRANCH --name-only | sed 's/^/\t/')"
		write_log "Only pulling diff files:$'\n'$filenames"
	fi

	ignore=""
	if [ -f '.git-ftp-ignore' ]; then
		ignore="$(grep -v '^#' .git-ftp-ignore | awk 'NF' | sed 's/^\(.*\)$/--exclude-glob "\1" /' | tr -d '\r\n')"
	fi
	ignore+=" --exclude=^\.git/ --exclude=^\.git-ftp\.log --exclude=^\.git-ftp-ignore"

	lftp_command="set ftp:list-options -a && mirror$mirror_options $delete $ignoreall $include $ignore . $SYNCROOT && wait all && exit"
	out="$(lftp $LFTP_OPTIONS -e "$lftp_command" -u "${REMOTE_USER},${REMOTE_PASSWD}" "${REMOTE_PROTOCOL}://${REMOTE_HOST}/${REMOTE_PATH}" 2>&1)"
	print_info "$out"
}

set_scope() {
	[ -z "$SCOPE" ] && print_error_and_die "Missing scope argument." "$ERROR_MISSING_ARGUMENTS"
	[ -z "$URL" ] && print_error_and_die "Missing URL." "$ERROR_MISSING_ARGUMENTS"

	# URI without credentials
	if ! echo "$URL" | grep -q '@'; then
		git config "git-ftp.$SCOPE.url" "$URL"
		return
	fi

	# set url
	local protocol=$(get_protocol_of_url "$URL")
	local path="${URL##*@}"
	git config "git-ftp.$SCOPE.url" "${protocol}://${path}"

	# strip protocol
	local credentials=${URL#${protocol}://}
	# cut at last '@' occurrence
	local credentials=${credentials%${URL##*@}}
	# strip trailing '@'
	local credentials=${credentials%?}

	local colons=${credentials//[^:]/}
	case ${#colons} in
		0)
			# assume only username
			git config "git-ftp.$SCOPE.user" "${credentials}"
			;;
		1)
			# credentials have both username and password
			git config "git-ftp.$SCOPE.user" "${credentials%:*}"
			git config "git-ftp.$SCOPE.password" "${credentials#*:}"
			;;
		*)
			# we can't know where to cut with multiple ':'
			print_info "Warning, multiple ':' characters detected, only URL was set in scope."
			print_info "Use --user and --passwd options to set login and password respectively."
	esac
}

remove_scope() {
	[ -z "$SCOPE" ] && print_error_and_die "Missing scope argument." "$ERROR_MISSING_ARGUMENTS"

	git config --remove-section "git-ftp.$SCOPE" &>/dev/null

	[ $? -ne 0 ] && print_error_and_die "Cannot find scope $SCOPE." "$ERROR_GIT"
	print_info "Successfully removed scope $SCOPE."
}

set_current_branch() {
	local current="$( (git symbolic-ref HEAD 2> /dev/null || git rev-parse HEAD 2> /dev/null) | sed "s#^refs/heads/##")"
	if [ "$?" -ne "0" ]; then
		set_local_sha1
		current="$LOCAL_SHA1"
	fi
	write_log "currently on branch $current"
	CURRENT_BRANCH="$current"
}

fetch_remote() {
	download_remote_updates
	[ $DRY_RUN -ne 1 ] || return
	git add --all
	git commit -m '[git-ftp] remotely untracked modifications' -m "`git diff HEAD --name-status`" | grep -v '^#'
	set_local_sha1
	upload_local_sha1
}

handle_fetch() {
	local old_sha1=$DEPLOYED_SHA1
	git checkout $DEPLOYED_SHA1 2> /dev/null
	# If .gitignore changes between commits, untracked file can remain.
	# These files are preserved in a stash record.
	local stash=$(git stash -u)
	remote_lock
	fetch_remote
	release_remote_lock
	[ "$stash" != 'No local changes to save' ] && git stash pop
	git checkout "$CURRENT_BRANCH" 2> /dev/null
	if [ $DRY_RUN -ne 1 ] && [ $old_sha1 != $LOCAL_SHA1 ]; then
		print_info "From $REMOTE_HOST/$REMOTE_PATH"
		print_info "   $old_sha1..$LOCAL_SHA1"
	fi
}

# ------------------------------------------------------------
# Actions
# ------------------------------------------------------------
action_init() {
	check_git_version
	check_is_git_project
	check_is_dirty_repository
	set_branch
	set_remotes
	check_curl_access
	check_remote_access
	check_deployed_sha1
	set_local_sha1
	set_changed_files
	pre_push_hook
	remote_lock
	handle_file_sync
	upload_local_sha1
	release_remote_lock
	post_push_hook
	unset_branch
}

action_push() {
	check_git_version
	check_is_git_project
	check_is_dirty_repository
	set_branch
	set_remotes
	check_curl_access
	set_deployed_sha1_for_push
	set_local_sha1
	set_changed_files
	pre_push_hook
	remote_lock
	handle_file_sync
	upload_local_sha1
	release_remote_lock
	post_push_hook
	unset_branch
}

action_catchup() {
	check_is_git_project
	check_is_dirty_repository
	set_branch
	set_remotes
	check_curl_access
	set_local_sha1
	upload_local_sha1
	submodule_catchup
	unset_branch
}

action_show() {
	set_remotes
	check_curl_access
	DEPLOYED_SHA1="$(get_file_content "$DEPLOYED_SHA1_FILE")"
	check_exit_status "Could not get uploaded log file" "$ERROR_DOWNLOAD"
	git show "$DEPLOYED_SHA1"
}

action_log() {
	set_remotes
	check_curl_access
	DEPLOYED_SHA1="$(get_file_content "$DEPLOYED_SHA1_FILE")"
	check_exit_status "Could not get uploaded log file" "$ERROR_DOWNLOAD"
	git log "$DEPLOYED_SHA1"
}

action_download() {
	check_lftp_available
	check_is_git_project
	check_is_dirty_repository
	check_for_untracked_files
	set_remotes
	check_curl_access
	remote_lock
	download_remote_updates
	release_remote_lock
}

action_pull() {
	check_lftp_available
	check_is_git_project
	check_is_dirty_repository
	set_current_branch
	set_remotes
	check_curl_access
	set_deployed_sha1
	handle_fetch
	git merge $MERGE_ARGS $LOCAL_SHA1
}

action_snapshot() {
	check_lftp_available
	set_remotes
	check_curl_access
	init_new_repository
	download_remote_updates
	commit_snapshot
	action_catchup
}

action_add_scope() {
	check_is_git_project
	set_scope
}

action_remove_scope() {
	check_is_git_project
	remove_scope
}
# ------------------------------------------------------------
# Checks
# ------------------------------------------------------------
check_curl_access() {
	write_log "Check if curl is functional."
	command -v curl >/dev/null 2>&1
	check_exit_status "curl is not available" "$ERROR_DOWNLOAD"

	local curl_protocol="$REMOTE_PROTOCOL"
	# The ftpes protocol is FTP + SSL
	if [ "$curl_protocol" == "ftpes" ]; then
		curl_protocol="ftp"
		curl --version | grep "^Features: " | grep -qw "SSL"
		check_exit_status "Protocol '$REMOTE_PROTOCOL' not supported by curl" "$ERROR_DOWNLOAD"
	fi
	curl --version | grep "^Protocols: " | grep -qw "$curl_protocol"
	check_exit_status "Protocol '$REMOTE_PROTOCOL' not supported by curl" "$ERROR_DOWNLOAD"
}
check_remote_access() {
	write_log "Check if $REMOTE_BASE_URL_DISPLAY is accessible."
	set_default_curl_options
	CURL_ARGS+=(--ftp-create-dirs)
	CURL_ARGS+=("$REMOTE_BASE_URL/$REMOTE_PATH")
	curl "${CURL_ARGS[@]}" > /dev/null
	check_exit_status "Can't access remote '$REMOTE_BASE_URL_DISPLAY'" "$ERROR_DOWNLOAD"
}

check_deployed_sha1() {
	write_log "Check if $REMOTE_BASE_URL_DISPLAY/$REMOTE_PATH is clean."
	DEPLOYED_SHA1="$(get_file_content "$DEPLOYED_SHA1_FILE")"
	if [ "$DEPLOYED_SHA1" != "" ]; then
		print_error_and_die "Commit found, use 'git ftp push' to sync. Exiting..." "$ERROR_USAGE"
	fi
	# Make sure if sync all files if no sha1 was found
	IGNORE_DEPLOYED=1
}

check_git_version() {
	local GIT_VERSION="$(git --version | cut -d ' ' -f 3)"
	local MAJOR="$(echo "$GIT_VERSION" | cut -d '.' -f 1)"
	local MINOR="$(echo "$GIT_VERSION" | cut -d '.' -f 2)"
	if [ "$MAJOR" -lt 2 ] && [ "$MINOR" -lt 7 ]; then
		print_error_and_die "Git is too old, 1.7.0 or higher supported only." "$ERROR_GIT"
	fi
}

check_remote_lock() {
	write_log "Checking remote lock."
	local LCK_CONTENT="$(get_file_content "$REMOTE_LCK_FILE" 2>/dev/null)"
	if [ -n "$LCK_CONTENT" ]; then
		local LCK_SHA1=$(echo "$LCK_CONTENT" | head -n 1)
		write_log "Remote lock sha1 $LCK_SHA1."
		write_log "Local sha1 $LOCAL_SHA1."
		if [ "$LCK_SHA1" != "$LOCAL_SHA1" ]; then
			local LCK_USER=$(echo "$LCK_CONTENT" | tail -n 1)
			print_error_and_die "Remote locked by $LCK_USER." "$ERROR_REMOTE_LOCKED"
		fi
	fi
}

check_is_git_project() {
	local git_project_dir="$(git rev-parse --show-toplevel 2>/dev/null)"
	[ -z "$git_project_dir" ] &&  print_error_and_die "Not a Git project? Exiting..." "$ERROR_GIT"
	cd "$git_project_dir"
}

check_is_dirty_repository() {
	[ "$(git status -uno --porcelain | wc -l)" -ne 0 ] && print_error_and_die "Dirty repository: Having uncommitted changes. Exiting..." "$ERROR_GIT"
}

check_for_untracked_files() {
	[ $(git status --porcelain | wc -l) -ne 0 ] && print_error_and_die "Dirty repository: Having untracked files. Exiting..." $ERROR_GIT
}

check_lftp_available() {
	command -v lftp > /dev/null || print_error_and_die "lftp not found. This operation requires lftp installed." $ERROR_GIT
}

# ------------------------------------------------------------
# Main
# ------------------------------------------------------------
main() {
	cache_git_submodules
	handle_action
	cleanup
	print_error_log
	exit 0
}

write_log "git-ftp version $VERSION running on $(uname -a)"

# 2 args are needed: action and url
if [ $# = 0 ]; then
	usage;
fi

while test $# != 0
do
	case "$1" in
		init|push|catchup|show|download|pull|add-scope|remove-scope|log|snapshot)
			ACTION="$1"
			# catch scope
			if [ "$1" == "add-scope" ] || [ "$1" == "remove-scope" ]; then
				SCOPE="$2"
				if ! echo "$SCOPE" | grep -q '^[-0-9a-zA-Z_]*$' ; then
					print_error_and_die "Invalid scope name." "$ERROR_USAGE"
				fi
				shift
			fi
			;;
		-h|--h|--he|--hel|--help|help)
			usage_long
			;;
		-u|--user*)
			case "$#,$1" in
				*,*=*)
					REMOTE_USER=$(expr "z$1" : 'z-[^=]*=\(.*\)')
					;;
				1,*)
					REMOTE_USER="$USER"
					;;
				*)
					if ! echo "$2" | egrep -q '^-'; then
						REMOTE_USER="$2"
						shift
					else
						REMOTE_USER="$USER"
					fi
					;;
			esac
			;;
		-s|--scope*)
			case "$#,$1" in
				*,*=*)
					SCOPE=$(expr "z$1" : 'z-[^=]*=\(.*\)')
					;;
				1,*)
					check_is_git_project && SCOPE="$(git rev-parse --abbrev-ref HEAD)"
					;;
				*)
					if ! echo "$2" | egrep -q '^-'; then
						SCOPE="$2"
						shift
					else
						check_is_git_project && SCOPE="$(git rev-parse --abbrev-ref HEAD)"
					fi
					;;
			esac
			if ! echo "$SCOPE" | grep -q '^[-0-9a-zA-Z_]*$' ; then
				print_error_and_die "Invalid scope name." "$ERROR_USAGE"
			fi
			write_log "Using scope $SCOPE if available"
			;;
		-b|--branch*)
			case "$#,$1" in
				*,*=*)
					BRANCH=$(expr 'z$1' : 'z-[^=]*=\(.*\)')
					;;
				1,*)
					print_error_and_die "Too few arguments for option --branch." "$ERROR_MISSING_ARGUMENTS"
					;;
				*)
					if ! echo "$2" | egrep -q '^-'; then
						BRANCH="$2"
						shift
					else
						print_error_and_die "Too few arguments for option --branch." "$ERROR_MISSING_ARGUMENTS"
					fi
					;;
			esac
			;;
		--syncroot*)
			case "$#,$1" in
				*,*=*)
					SYNCROOT="$(expr "z$1" : 'z-[^=]*=\(.*\)')"
					;;
				1,*)
					print_error_and_die "Too few arguments for option --syncroot." "$ERROR_MISSING_ARGUMENTS"
					;;
				*)
					if ! echo "$2" | egrep -q '^-'; then
						SYNCROOT="$2"
						shift
					else
						print_error_and_die "Too few arguments for option --syncroot." "$ERROR_MISSING_ARGUMENTS"
					fi
					;;
			esac
			write_log "Using syncroot $SYNCROOT if exists."
			;;
		-c|--commit*)
			case "$#,$1" in
				*,*=*)
					DEPLOYED_SHA1=$(expr "z$1" : 'z-[^=]*=\(.*\)')
					;;
				1,*)
					print_error_and_die "Too few arguments for option -c." "$ERROR_MISSING_ARGUMENTS"
					;;
				*)
					if ! echo "$2" | egrep -q '^-'; then
						DEPLOYED_SHA1="$2"
						shift
					else
						print_error_and_die "Too few arguments for option -c." "$ERROR_MISSING_ARGUMENTS"
					fi
					;;
			esac
			write_log "Using commit $DEPLOYED_SHA1 as deployed."
			;;
		-p|--passwd*)
			case "$#,$1" in
				*,*=*)
					REMOTE_PASSWD=$(expr "z$1" : 'z-[^=]*=\(.*\)')
					;;
				1,*)
					print_error_and_die "Too few arguments for option -p." "$ERROR_MISSING_ARGUMENTS"
					;;
				*)
					if ! echo "$2" | egrep -q '^-'; then
						REMOTE_PASSWD="$2"
						shift
					else
						print_error_and_die "Too few arguments for option -p." "$ERROR_MISSING_ARGUMENTS"
					fi
					;;
			esac
			;;
		-P|--ask-passwd)
			ask_for_passwd
			;;
		-k|--keychain*)
			USE_KEYCHAIN=1
			write_log "Enabled keychain."
			case "$#,$1" in
				*,*=*)
					KEYCHAIN_USER=$(expr "z$1" : 'z-[^=]*=\(.*\)')
					;;
				1,*)
					# Nothing is handed over, this is okay
					;;
				*)
					if ! echo "$2" | egrep -q '^-'; then
						KEYCHAIN_USER="$2"
						shift
					fi
					;;
			esac
			;;
		-a|--all)
			IGNORE_DEPLOYED=1
			;;
		-l|--lock)
			if [ $ENABLE_REMOTE_LCK -ne 1 ]; then
				write_log "Enabling remote locking feature."
				ENABLE_REMOTE_LCK=1
			else
				write_log "Disabling remote locking feature."
				ENABLE_REMOTE_LCK=0
			fi
			;;
		-D|--dry-run)
			DRY_RUN=1
			write_log "Running dry, won't do anything."
			;;
		-n|--silent)
			VERBOSE=-1
			REMOTE_CMD_OPTIONS=("-s")
			;;
		-v|--verbose)
			VERBOSE=1
			[ -n "$LOG_CACHE" ] && echo -e "$LOG_CACHE"
			REMOTE_CMD_OPTIONS=()
			;;
		-vv)
			VERBOSE=1
			[ -n "$LOG_CACHE" ] && echo -e "$LOG_CACHE"
			REMOTE_CMD_OPTIONS=("-v")
			LFTP_OPTIONS="-d"
			;;
		-f|--force)
			FORCE=1
			write_log "Forced mode enabled."
			;;
		--version|version)
			echo "git-ftp version $VERSION"
			exit 0
			;;
		--insecure)
			CURL_INSECURE=1
			write_log "Insecure SSL/TLS connection allowed"
			;;
		--cacert*)
			case "$#,$1" in
				*,*=*)
					REMOTE_CACERT=$(expr "z$1" : 'z-[^=]*=\(.*\)')
					;;
				1,*)
					print error_and_die "Too few arguments for option --cacert" "$ERROR_MISSING_ARGUMENTS"
					;;
				*)
					if ! echo "$2" | egrep -q '^-'; then
						REMOTE_CACERT="$2"
						shift
					else
						print_error_and_die "Too few arguments for option --cacert" "$ERROR_MISSING_ARGUMENTS"
					fi
					;;
			esac
			;;
		--key)
			case "$#,$1" in
				*,*=*)
					CURL_PRIVATE_KEY=$(expr "z$1" : 'z-[^=]*=\(.*\)')
					;;
				1,*)
					print_error_and_die "Too few arguments for option --key." "$ERROR_MISSING_ARGUMENTS"
					;;
				*)
					if ! echo "$2" | egrep -q '^-'; then
						CURL_PRIVATE_KEY="$2"
						shift
					else
						print_error_and_die "Too few arguments for option --key." "$ERROR_MISSING_ARGUMENTS"
					fi
					;;
			esac
			;;
		--pubkey)
			case "$#,$1" in
				*,*=*)
					CURL_PUBLIC_KEY=$(expr "z$1" : 'z-[^=]*=\(.*\)')
					;;
				1,*)
					print_error_and_die "Too few arguments for option --pubkey." "$ERROR_MISSING_ARGUMENTS"
					;;
				*)
					if ! echo "$2" | egrep -q '^-'; then
						CURL_PUBLIC_KEY="$2"
						shift
					else
						print_error_and_die "Too few arguments for option --pubkey." "$ERROR_MISSING_ARGUMENTS"
					fi
					;;
			esac
			;;
		-A|--active)
			ACTIVE_MODE=1
			write_log "Using active mode."
			;;
		--no-commit)
			MERGE_ARGS="$MERGE_ARGS --no-commit"
			write_log "Adding --no-commit to merge arguments: $MERGE_ARGS"
			;;
		--changed-only)
			DOWNLOAD_CHANGED_ONLY=1
			write_log "Downloading only changed files."
			;;
		--disable-epsv)
			if [ $ACTIVE_MODE -eq 0 ]; then
				CURL_DISABLE_EPSV=1
				write_log "Disabling EPSV."
			fi
			;;
		--remote-root)
			REMOTE_ROOT="$2"
			shift
			;;
		--no-verify)
			EXECUTE_HOOKS=0
			shift
			;;
		--enable-post-errors)
			ENABLE_POST_HOOK_ERRORS=1
			shift
			;;
		--auto-init)
			if [ $AUTO_INIT -eq 0 ]; then
				AUTO_INIT=1
				write_log "Auto init if needed."
			fi
			;;
		-x|--proxy*)
			case "$#,$1" in
				*,*=*)
					CURL_PROXY=$(expr "z$1" : 'z-[^=]*=\(.*\)')
					;;
				1,*)
					print_error_and_die "Too few arguments for option --proxy." "$ERROR_MISSING_ARGUMENTS"
					;;
				*)
					if ! echo "$2" | egrep -q '^-'; then
						CURL_PROXY="$2"
						shift
					else
						print_error_and_die "Too few arguments for option --proxy." "$ERROR_MISSING_ARGUMENTS"
					fi
					;;
			esac
			;;
		*)
			# Pass thru anything that may be meant for fetch.
			if [ -n "$1" ]; then
				if [ -z "$URL" ]; then
					URL="$1"
				elif [ "$ACTION" == "snapshot" -a -z "$SNAPSHOT_DIR" ]; then
					SNAPSHOT_DIR="$1"
				else
					print_error_and_die "Unrecognised option: $1" "$ERROR_MISSING_ARGUMENTS"
				fi
			fi
			;;
	esac
	shift
done
main