Duply-code

From duply
Jump to: navigation, search

duply sourcecode

duply's svn repository is not the most recent source for the code. Usually the svn only gets updated on releases. But not always. Development snapshots are taken daily. These are not guaranteed to work, but might contain unreleased fixes. Check the snapshot's changelog header accordingly.

SVN access

Browse the repository

http://ftplicity.svn.sourceforge.net/viewvc/ftplicity/duply/trunk/

SVN access

svn co https://ftplicity.svn.sourceforge.net/svnroot/ftplicity/duply/trunk duply

SVN Log

http://ftplicity.svn.sourceforge.net/viewvc/ftplicity/duply/?view=log

Latest Development Snapshot

mod time 2018-05-26

plain/text -> http://duply.net/tmp/duply.sh

  1. #!/usr/bin/env bash
  2. #
  3. ################################################################################
  4. # duply (grown out of ftplicity), is a shell front end to duplicity that #
  5. # simplifies the usage by managing settings for backup jobs in profiles. #
  6. # It supports executing multiple commands in a batch mode to enable single #
  7. # line cron entries and executes pre/post backup scripts. #
  8. # Since version 1.5.0 all duplicity backends are supported. Hence the name #
  9. # changed from ftplicity to duply. #
  10. # See http://duply.net or http://ftplicity.sourceforge.net/ for more info. #
  11. # (c) 2006 Christiane Ruetten, Heise Zeitschriften Verlag, Germany #
  12. # (c) 2008-2018 Edgar Soldin (changes since version 1.3) #
  13. ################################################################################
  14. # LICENSE: #
  15. # This program is licensed under GPLv2. #
  16. # Please read the accompanying license information in gpl.txt. #
  17. ################################################################################
  18. # TODO/IDEAS/KNOWN PROBLEMS:
  19. # - possibility to restore time frames (incl. deleted files)
  20. # realizable by listing each backup and restore from
  21. # oldest to the newest, problem: not performant
  22. # - search file in all backups function and show available
  23. # versions with backups date (list old avail since 0.6.06)
  24. # - edit profile opens conf file in vi
  25. # - implement log-fd interpretation
  26. # - add a duplicity option check against the options pending
  27. # deprecation since 0.5.10 namely --time-separator
  28. # --short-filenames
  29. # --old-filenames
  30. # - add 'exclude_<command>' list usage eg. exclude_verify
  31. # - featreq 25: a download/install duplicity option
  32. # - hint on install software if a piece is missing
  33. # - import/export profile from/to .tgz function !!!
  34. #
  35. # CHANGELOG:
  36. # 2.1 ()
  37. # - be more verbose when duplicity version detection fails
  38. # - using info shows python binary's path for easier identification now
  39. # - reworked python interpreter handling, it's either
  40. # configured per PYTHON var
  41. # unconfigured, parsed from duplicity shebang
  42. # or set to current duplicity default 'python2' (was 'python' until now)
  43. # - do not quotewrap strings because of slashes (eg. paths) anymore
  44. #
  45. # 2.0.4 (20.02.2018)
  46. # - bugfix 114: "duply usage is not current" wrt. purgeFull/Incr
  47. # - bugfix 115: typo in error message - "Not GPG_KEY entries" should be "No"
  48. # - bugfix 117: no duply_ prefix when ARCH_DIR is set in conf
  49. # - bugfix debian 882159: duply: occasionally shows negative runtimes
  50. #
  51. # 2.0.3 (29.08.2017)
  52. # - bugfix: "line 2231: CMDS: bad array subscript"
  53. # - bugfix 112: "env: illegal option -- u" on MacOSX
  54. #
  55. # 2.0.2 (23.05.2017)
  56. # - bugfix: never insert creds into file:// targets
  57. # - bugfix: avail profiles hint sometimes shortend the names by one char
  58. # - bugfix 108: CMD_NEXT variable should ignore conditional commands (and, or)
  59. # - export condition before/after next/prev command as CND_PREV,CND_NEXT now
  60. # - bugfix 97: Unknown command should be ERROR, not WARNING
  61. #
  62. # 2.0.1 (16.11.2016)
  63. # - bugfix 104: Duply 2.0 sets wrong archive dir, --name was always 'duply_'
  64. #
  65. # 2.0 (27.10.2016)
  66. # made this a major version change, as we broke backward compatibility anyway
  67. # (see last change in v1.10). got complaints that rightfully pointed out
  68. # that should only come w/ a major version change. so, here we go ;)
  69. # if your backend stops working w/ this version create a new profile and
  70. # export the env vars needed as described in the comments of the conf file
  71. # directly above the SOURCE setting.
  72. # Changes:
  73. # - making sure multi spaces in TARGET survive awk processing
  74. # - new env var PROFILE exported to scripts
  75. # - fix 102: expose a unique timestamp variable for pre/post scripts
  76. # actually a featreq. exporting RUN_START nanosec unix timestamp
  77. # - fix 101: GPG_AGENT_INFO is 'bogus' (thx Thomas Harning Jr.)
  78. # - fix 96: duply cannot handle two consecutive spaces in paths
  79. #
  80. # 1.11.3 (29.5.2016)
  81. # - fix wrong "WARNING: No running gpg-agent ..." when sign key was not set
  82. #
  83. # 1.11.2 (11.2.2016)
  84. # - fix "gpg: unsafe" version print out
  85. # - bugfix 91: v1.11 [r47] broke asymmetric encryption when using GPG_KEYS_ENC
  86. # - bugfix 90: S3: TARGET_USER/PASS have no effect, added additional
  87. # documentation about needed env vars to template conf file
  88. #
  89. # 1.11.1 (18.12.2015)
  90. # - bugfix 89: "Duply has trouble with PYTHON-interpreter" on OSX homebrew
  91. # - reverted duply's default PYTHON to 'python'
  92. #
  93. # 1.11 (24.11.2015)
  94. # - remove obsolete --ssh-askpass routine
  95. # - add PYTHON conf var to allow global override of used python interpreter
  96. # - enforced usage of "python2" in PATH as default interpreter for internal
  97. # use _and_ to run duplicity (setup.py changed the shebang to the fixed
  98. # path /usr/bin/python until 0.7.05, which we circumvent this way)
  99. # - featreq 36: support gpg-connect-agent as a means to detect if an agent is
  100. # running (thx Thomas Harning Jr.), used gpg-agent for detection though
  101. # - quotewrapped run_cmd parameters to protect it from spaces eg. in TMP path
  102. # - key export routine respects gpg-agent usage now
  103. #
  104. # 1.10.1 (19.8.2015)
  105. # - bugfix 86: Duply+Swift outputs warning
  106. # - bugfix 87: Swift fails without BACKEND_URL
  107. #
  108. # 1.10 (31.7.2015)
  109. # - featreq 37: busybox issues - fix awk, grep version detection,
  110. # fix grep failure because --color=never switch is unsupported
  111. # (thx Thomas Harning Jr. for reporting and helping to debug/fix it)
  112. # - bugfix 81: --exclude-globbing-filelist is deprecated since 0.7.03
  113. # (thx Joachim Wiedorn, also for maintaining the debian package)
  114. # - implemented base-/dirname as bash functions
  115. # - featreq 31 " Support for duplicity Azure backend " - ignored a
  116. # contributed patch by Scott McKenzie and instead opted for removing almost
  117. # all code that deals with special env vars required by backends.
  118. # adding and modifying these results in too much overhead so i dropped this
  119. # feature. the future alternative for users is to consult the duplicity
  120. # manpage and add the needed export definitions to the conf file.
  121. # appended a commented example to the template conf below the auth section.
  122. #
  123. # 1.9.2 (21.6.2015)
  124. # - bugfix: exporting keys with gpg2.1 works now (thx Philip Jocks)
  125. # - documented GPG_OPTS needed for gpg2.1 to conf template (thx Troy Engel)
  126. # - bugfix 82: GREP_OPTIONS=--color=always disrupted time calculation
  127. # - added GPG conf var (see conf template for details)
  128. # - added grep version output as it is an integral needed binary
  129. # - added PYTHONPATH printout in version output
  130. #
  131. # 1.9.1 (13.10.2014)
  132. # - export CMD_ERR now for scripts to detect if CMD_PREV failed/succeeded
  133. # - bugfix: CMD_PREV contained command even if it was skipped
  134. #
  135. # 1.9.0 (24.8.2014)
  136. # - bugfix: env vars were not exported when external script was executable
  137. # - rework GPG_KEY handling, allow virtually anything now (uid, keyid etc.)
  138. # see gpg manpage, section "How to specify a user ID"
  139. # let gpg complain when the delivered values are invalid for whatever reason
  140. # - started to rework tmp space checking, exposed folder & writable check
  141. # TODO: reimplement enough file space available checking
  142. #
  143. # 1.8.0 (13.7.2014)
  144. # - add command verifyPath to expose 'verify --file-to-restore' action
  145. # - add time parameter support to verify command
  146. # - add section time formats to usage output
  147. #
  148. # 1.7.4 (24.6.2014)
  149. # - remove ubuntu one support, service is discontinued
  150. # - featreq 31: add authenticated swift (contributed by Justus Seifert)
  151. #
  152. # 1.7.3 (3.4.2014)
  153. # - bugfix: test routines, gpg2 asked for passphrase although GPG_PW was set
  154. #
  155. # 1.7.2 (1.4.2014 "April,April")
  156. # - bugfix: debian Bug#743190 "duply no longer allows restoration without
  157. # gpg passphrase in conf file"
  158. # GPG_AGENT_INFO env var is now needed to trigger --use-agent
  159. # - bugfix: gpg keyenc test routines didn't work if GPG_PW was not set
  160. #
  161. # 1.7.1 (30.3.2014)
  162. # - bugfix: purge-* commands renamed to purgeFull, purgeIncr due to
  163. # incompatibility with new minus batch separator
  164. #
  165. # 1.7.0 (20.3.2014)
  166. # - disabled gpg key id plausibility check, too many valid possibilities
  167. # - featreq 7 "Halt if precondition fails":
  168. # added and(+), or(-) batch command(separator) support
  169. # - featreq 26 "pre/post script with shebang line":
  170. # if a script is flagged executable it's executed in a subshell
  171. # now as opposed to sourced to bash, which is the default
  172. # - bugfix: do not check if dpbx, swift credentials are set anymore
  173. # - bugfix: properly escape profile name, archdir if used as arguments
  174. # - add DUPL_PRECMD conf setting for use with e.g. trickle
  175. #
  176. # 1.6.0 (1.1.2014)
  177. # - support gs backend
  178. # - support dropbox backend
  179. # - add gpg-agent support to gpg test routines
  180. # - autoenable --use-agent if passwords were not defined in config
  181. # - GPG_OPTS are now honored everywhere, keyrings or complete gpg
  182. # homedir can thus be configured to be located anywhere
  183. # - always import both secret and public key if avail from config profile
  184. # - new explanatory comments in initial exclude file
  185. # - bugfix 7: Duply only imports one key at a time
  186. #
  187. # 1.5.11 (19.07.2013)
  188. # - purge-incr command for remove-all-inc-of-but-n-full feature added
  189. # patch provided by Moritz Augsburger, thanks!
  190. # - documented version command in man page
  191. #
  192. # 1.5.10 (26.03.2013)
  193. # - minor indent and documentation fixes
  194. # - bugfix: exclude filter failed on ubuntu, mawk w/o posix char class support
  195. # - bugfix: fix url_decoding generally and for python3
  196. # - bugfix 3609075: wrong script results in status line (thx David Epping)
  197. #
  198. # 1.5.9 (22.11.2012)
  199. # - bugfix 3588926: filter --exclude* params for restore/fetch ate too much
  200. # - restore/fetch now also ignores --include* or --exclude='foobar'
  201. #
  202. # 1.5.8 (26.10.2012)
  203. # - bugfix 3575487: implement proper cloud files support
  204. #
  205. # 1.5.7 (10.06.2012)
  206. # - bugfix 3531450: Cannot use space in target URL (file:///) anymore
  207. #
  208. # 1.5.6 (24.5.2012)
  209. # - commands purge, purge-full have no default value anymore for security
  210. # reasons; instead max value can be given via cmd line or must be set
  211. # in profile; else an error is shown.
  212. # - minor man page modifications
  213. #
  214. # versioning scheme will be simplified to [major].[minor].[patch] version
  215. # with the next version raise
  216. #
  217. # 1.5.5.5 (4.2.2012)
  218. # - bugfix 3479605: SEL context confused profile folder's permission check
  219. # - colon ':' in url passphrase got ignored, added python driven url_decoding
  220. # for user & pass to better process special chars
  221. #
  222. # 1.5.5.4 (16.10.2011)
  223. # - bugfix 3421268: SFTP passwords from conf ignored and always prompted for
  224. # - add support for separate sign passphrase (needs duplicity 0.6.14+)
  225. #
  226. # 1.5.5.3 (1.10.2011)
  227. # - bugfix 3416690: preview threw echo1 error
  228. # - fix unknown cmds error usage & friends if more than 2 params were given
  229. #
  230. # 1.5.5.2 (23.9.2011)
  231. # - bugfix 3409643: ssh key auth did ask for passphrase (--ssh-askpass ?)
  232. # - bugfix: mawk does not support \W and did not split multikey definitions
  233. # - all parameters should survive single (') and double (") quotes now
  234. #
  235. # 1.5.5.1 (7.6.2011)
  236. # - featreq 3311881: add ftps as supported by duplicity 0.6.13 (thx mape2k)
  237. # - bugfix 3312208: signing detection broke symmetric gpg test routine
  238. #
  239. # 1.5.5 (2.5.2011)
  240. # - bugfix: fetch problem with space char in path, escape all params
  241. # containing non word chars
  242. # - list available profiles, if given profile cannot be found
  243. # - added --use-agent configuration hint
  244. # - bugfix 3174133: --exclude* params in conf DUPL_PARAMS broke
  245. # fetch/restore
  246. # - version command now prints out 'using installed' info
  247. # - featreq 3166169: autotrust imported keys, based on code submitted by
  248. # Martin Ellis - imported keys are now automagically trusted ultimately
  249. # - new txt2man feature to create manpages for package maintainers
  250. #
  251. # 1.5.4.2 (6.1.2011)
  252. # - new command changelog
  253. # - bugfix 3109884: freebsd awk segfaulted on printf '%*', use print again
  254. # - bugfix: freebsd awk hangs on 'awk -W version'
  255. # - bugfix 3150244: mawk does not know '--version'
  256. # - minor help text improvements
  257. # - new env vars CMD_PREV,CMD_NEXT replacing CMD env var for scripts
  258. #
  259. # 1.5.4.1 (4.12.2010)
  260. # - output awk, python, bash version now in prolog
  261. # - shebang uses /usr/bin/env now for freebsd compatibility,
  262. # bash not in /bin/bash
  263. # - new --disable-encryption parameter,
  264. # to override profile encr settings for one run
  265. # - added exclude-if-present setting to conf template
  266. # - bug 3126972: GPG_PW only needed for signing/symmetric encryption
  267. # (even though duplicity still needs it)
  268. #
  269. # 1.5.4 (15.11.2010)
  270. # - as of 1.5.3 already, new ARCH_DIR config option
  271. # - multiple key support
  272. # - ftplicity-Feature Requests-2994929: separate encryption and signing key
  273. # - key signing of symmetric encryption possible (duplicity patch committed)
  274. # - gpg tests disable switch
  275. # - gpg tests now previewable and more intelligent
  276. #
  277. # 1.5.3 (1.11.2010)
  278. # - bugfix 3056628: improve busybox compatibility, grep did not have -m param
  279. # - bugfix 2995408: allow empty password for PGP key
  280. # - bugfix 2996459: Duply erroneously escapes '-' symbol in username
  281. # - url_encode function is now pythonized
  282. # - rsync uses FTP_PASSWORD now if duplicity 0.6.10+ , else issue warning
  283. # - feature 3059262: Make pre and post aware of parameters,
  284. # internal parameters + CMD of pre or post
  285. #
  286. # 1.5.2.3 (16.4.2010)
  287. # - bugfix: date again, should now work virtually anywhere
  288. #
  289. # 1.5.2.2 (3.4.2010)
  290. # - minor bugfix: duplicity 0.6.8b version string now parsable
  291. # - added INSTALL.txt
  292. #
  293. # 1.5.2.1 (23.3.2010)
  294. # - bugfix: date formatting is awked now and should work on all platforms
  295. #
  296. # 1.5.2 (2.3.2010)
  297. # - bugfix: errors print to STD_ERR now, failed tasks print an error message
  298. # - added --name=duply_<profile> for duplicity 0.6.01+ to name cache folder
  299. # - simplified & cleaned profileless commands, removed second instance
  300. # - generalized separator time routines
  301. # - added support for --no-encryption (GPG_KEY='disabled'), see conf examples
  302. # - minor fixes
  303. #
  304. # 1.5.1.5 (5.2.2010)
  305. # - bugfix: added special handling of credentials for rsync, imap(s)
  306. #
  307. # 1.5.1.4 (7.1.2010)
  308. # - bugfix: nsecs defaults now to zeroes if date does not deliver [0-9]{9}
  309. # - check if ncftp binary is available if url protocol is ftp
  310. # - bugfix: duplicity output is now printed to screen directly to resolve
  311. # 'mem alloc problem' bug report
  312. # - bugfix: passwords will not be in the url anymore to solve the 'duply shows
  313. # sensitive data in process listing' bug report
  314. #
  315. # 1.5.1.3 (24.12.2009) 'merry xmas'
  316. # - bugfix: gpg pass now apostrophed to allow space and friends
  317. # - bugfix: credentials are now url encoded to allow special chars in them
  318. # a note about url encoding has been added to the conf template
  319. #
  320. # 1.5.1.2 (1.11.2009)
  321. # - bugfix: open parenthesis in password broke duplicity execution
  322. # - bugfix: ssh/scp backend does not always need credentials e.g. key auth
  323. #
  324. # 1.5.1.1 (21.09.2009)
  325. # - bugfix: fixed s3[+http] TARGET_PASS not needed routine
  326. # - bugfix: TYPO in duply 1.5.1 prohibited the use of /etc/duply
  327. # see https://sourceforge.net/tracker/index.php?func=detail&
  328. # aid=2864410&group_id=217745&atid=1041147
  329. #
  330. # 1.5.1 (21.09.2009) - duply (fka. ftplicity)
  331. # - first things first: ftplicity (being able to support all backends since
  332. # some time) will be called duply (fka. ftplicity) from now on. The addendum
  333. # is for the time being to circumvent confusion.
  334. # - bugfix: exit code is 1 (error) not 0 (success), if at least on duplicity
  335. # command failed
  336. # - s3[+http] now supported natively by translating user/pass to access_key/
  337. # secret_key environment variables needed by duplicity s3 boto backend
  338. # - bugfix: additional output lines do not confuse version check anymore
  339. # - list command supports now age parameter (patch by stefan on feature
  340. # request tracker)
  341. # - bugfix: option/param pairs are now correctly passed on to duplicity
  342. # - bugfix: s3[+http] needs no TARGET_PASS if command is read only
  343. #
  344. # 1.5.0.2 (31.07.1009)
  345. # - bugfix: insert password in target url didn't work with debian mawk
  346. # related to previous bug report
  347. #
  348. # 1.5.0.1 (23.07.2009)
  349. # - bugfix: gawk gensub dependency raised an error on debian's default mawk
  350. # replaced with match/substr command combination (bug report)
  351. # https://sf.net/tracker/?func=detail&atid=1041147&aid=2825388&
  352. # group_id=217745
  353. #
  354. # 1.5.0 (01.07.2009)
  355. # - removed ftp limitation, all duplicity backends should work now
  356. # - bugfix: date for separator failed on openwrt busybox date, added a
  357. # detecting workaround, milliseconds are not available w/ busybox date
  358. #
  359. # 1.4.2.1 (14.05.2009)
  360. # - bugfix: free temp space detection failed with lvm, fixed awk parse routine
  361. #
  362. # 1.4.2 (22.04.2009)
  363. # - gpg keys are now exported as gpgkey.[id].asc , the suffix reflects the
  364. # armored ascii nature, the id helps if the key is switched for some reason
  365. # im/export routines are updated accordingly (import is backward compatible
  366. # to the old profile/gpgkey files)
  367. # - profile argument is treated as path if it contains slashes
  368. # (for details see usage)
  369. # - non-ftplicity options (all but --preview currently) are now passed
  370. # on to duplicity
  371. # - removed need for stat in secure_conf, it is ls based now
  372. # - added profile folder readable check
  373. # - added gpg version & home info output
  374. # - awk utility availability is now checked, because it was mandatory already
  375. # - tmp space is now checked on writability and space requirement
  376. # test fails on less than 25MB or configured $VOLSIZE,
  377. # test warns if there is less than two times $VOLSIZE because
  378. # that's required for --asynchronous-upload option
  379. # - gpg functionality is tested now before executing duplicity
  380. # test drive contains encryption, decryption, comparison, cleanup
  381. # this is meant to detect non trusted or other gpg errors early
  382. # - added possibility of doing symmetric encryption with duplicity
  383. # set GPG_KEY="" or simply comment it out
  384. # - added hints in config template on the depreciation of
  385. # --short-filenames, --time-separator duplicity options
  386. #
  387. # new versioning scheme 1.4.2b => 1.4.2,
  388. # beta b's are replaced by a patch count number e.g. 1.4.2.1 will be assigned
  389. # to the first bug fixing version and 1.4.2.2 to the second and so on
  390. # also the releases will now have a release date formatted (Day.Month.Year)
  391. #
  392. # 1.4.1b1 - bugfix: ftplicity changed filesystem permission of a folder
  393. # named exactly as the profile if existing in executing dir
  394. # - improved plausibility checking of config and profile folder
  395. # - secure_conf only acts if needed and prints a warning now
  396. #
  397. # 1.4.1b - introduce status (duplicity collection-status) command
  398. # - pre/post script output printed always now, not only on errors
  399. # - new config parameter GPG_OPTS to pass gpg options
  400. # added examples & comments to profile template conf
  401. # - reworked separator times, added duration display
  402. # - added --preview switch, to preview generated command lines
  403. # - disabled MAX_AGE, MAX_FULL_BACKUPS, VERBOSITY in generated
  404. # profiles because they have reasonable defaults now if not set
  405. #
  406. # 1.4.0b1 - bugfix: incr forces incremental backups on duplicity,
  407. # therefore backup translates to pre_bkp_post now
  408. # - bugfix: new command bkp, which represents duplicity's
  409. # default action (incr or full if full_if_older matches
  410. # or no earlier backup chain is found)
  411. #
  412. # new versioning scheme 1.4 => 1.4.0, added new minor revision number
  413. # this is meant to slow down the rapid version growing but still keep
  414. # versions cleanly separated.
  415. # only additional features will raise the new minor revision number.
  416. # all releases start as beta, each bugfix release will raise the beta
  417. # count, usually new features arrive before a version 'ripes' to stable
  418. #
  419. # 1.4.0b
  420. # 1.4b - added startup info on version, time, selected profile
  421. # - added time output to separation lines
  422. # - introduced: command purge-full implements duplicity's
  423. # remove-all-but-n-full functionality (patch by unknown),
  424. # uses config variable $MAX_FULL_BACKUPS (default = 1)
  425. # - purge config var $MAX_AGE defaults to 1M (month) now
  426. # - command full does not execute pre/post anymore
  427. # use batch command pre_full_post if needed
  428. # - introduced batch mode cmd1_cmd2_etc
  429. # (in turn removed the bvp command)
  430. # - unknown/undefined command issues a warning/error now
  431. # - bugfix: version check works with 0.4.2 and older now
  432. # 1.3b3 - introduced pre/post commands to execute/debug scripts
  433. # - introduced bvp (backup, verify, purge)
  434. # - bugfix: removed need for awk gensub, now mawk compatible
  435. # 1.3b2 - removed pre/post need executable bit set
  436. # - profiles now under ~/.ftplicity as folders
  437. # - root can keep profiles in /etc/ftplicity, folder must be
  438. # created by hand, existing profiles must be moved there
  439. # - removed ftplicity in path requirement
  440. # - bugfix: bash < v.3 did not know '=~'
  441. # - bugfix: purge works again
  442. # 1.3 - introduces multiple profiles support
  443. # - modified some script errors/docs
  444. # - reordered gpg key check import routine
  445. # - added 'gpg key id not set' check
  446. # - added error_gpg (adds how to setup gpg key howto)
  447. # - bugfix: duplicity 0.4.4RC4+ parameter syntax changed
  448. # - duplicity_version_check routine introduced
  449. # - added time separator, shortnames, volsize, full_if_older
  450. # duplicity options to config file (inspired by stevie
  451. # from http://weareroot.de)
  452. # 1.1.1 - bugfix: encryption reactivated
  453. # 1.1 - introduced config directory
  454. # 1.0 - first release
  455. ################################################################################
  456.  
  457. # utility functions overriding binaries
  458.  
  459. # wrap grep to override possible env set GREP_OPTIONS=--color=always
  460. function grep {
  461. command env "GREP_OPTIONS=" grep "$@"
  462. }
  463.  
  464. # implement basename in plain bash
  465. function basename {
  466. local stripped="${1%/}"
  467. echo "${stripped##*/}"
  468. }
  469.  
  470. # implement dirname in plain bash
  471. function dirname {
  472. echo ${1%/*}
  473. }
  474.  
  475. # implement basic which in plain bash
  476. function which {
  477. type -p "$@"
  478. }
  479.  
  480. # check availability of executables via file name or file paths
  481. function lookup {
  482. local bin="$1"
  483. # look for file names in path via bash hash OR
  484. # look for executables at given relative/absolute location
  485. ( [ "${bin##*/}" == "$bin" ] && hash "$bin" 2>/dev/null ) || [ -x "$bin" ]
  486. }
  487.  
  488. # the python binary to use, exit code 0 when configured, else 1
  489. function python_binary {
  490. # if unset, parse from duplicity shebang
  491. if ! var_isset 'PYTHON'; then
  492. duplicity_python_binary_parse;
  493. echo $DUPL_PYTHON_BIN;
  494. return 1;
  495. else
  496. # tell if PYTHON was configured manually
  497. echo $PYTHON;
  498. return 0
  499. fi
  500. }
  501.  
  502. # important definitions #######################################################
  503.  
  504. ME_LONG="$0"
  505. ME="$(basename $0)"
  506. ME_NAME="${ME%%.*}"
  507. ME_VERSION="2.1dev"
  508. ME_WEBSITE="http://duply.net"
  509.  
  510. # default config values
  511. DEFAULT_SOURCE='/path/of/source'
  512. DEFAULT_TARGET='scheme://user[:password]@host[:port]/[/]path'
  513. DEFAULT_TARGET_USER='_backend_username_'
  514. DEFAULT_TARGET_PASS='_backend_password_'
  515. DEFAULT_GPG='gpg'
  516. DEFAULT_GPG_KEY='_KEY_ID_'
  517. DEFAULT_GPG_PW='_GPG_PASSWORD_'
  518. DEFAULT_PYTHON='python2'
  519.  
  520. # function definitions ##########################
  521.  
  522. function set_config { # sets global config vars
  523. local CONFHOME_COMPAT="$HOME/.ftplicity"
  524. local CONFHOME="$HOME/.duply"
  525. local CONFHOME_ETC_COMPAT="/etc/ftplicity"
  526. local CONFHOME_ETC="/etc/duply"
  527.  
  528. # confdir can be delivered as path (must contain /)
  529. if [ `echo $FTPLCFG | grep /` ] ; then
  530. CONFDIR=$(readlink -f $FTPLCFG 2>/dev/null || \
  531. ( echo $FTPLCFG|grep -v '^/' 1>/dev/null 2>&1 \
  532. && echo $(pwd)/${FTPLCFG} ) || \
  533. echo ${FTPLCFG})
  534. # or DEFAULT in home/.duply folder (NEW)
  535. elif [ -d "${CONFHOME}" ]; then
  536. CONFDIR="${CONFHOME}/${FTPLCFG}"
  537. # or in home/.ftplicity folder (OLD)
  538. elif [ -d "${CONFHOME_COMPAT}" ]; then
  539. CONFDIR="${CONFHOME_COMPAT}/${FTPLCFG}"
  540. warning_oldhome "${CONFHOME_COMPAT}" "${CONFHOME}"
  541. # root can put profiles under /etc/duply (NEW) if path exists
  542. elif [ -d "${CONFHOME_ETC}" ] && [ "$EUID" -eq 0 ]; then
  543. CONFDIR="${CONFHOME_ETC}/${FTPLCFG}"
  544. # root can keep profiles under /etc/ftplicity (OLD) if path exists
  545. elif [ -d "${CONFHOME_ETC_COMPAT}" ] && [ "$EUID" -eq 0 ]; then
  546. CONFDIR="${CONFHOME_ETC_COMPAT}/${FTPLCFG}"
  547. warning_oldhome "${CONFHOME_ETC_COMPAT}" "${CONFHOME_ETC}"
  548. # hmm no profile folder there, then use default for error later
  549. else
  550. CONFDIR="${CONFHOME}/${FTPLCFG}" # continue, will fail later in main
  551. fi
  552.  
  553. # remove trailing slash, get profile name etc.
  554. CONFDIR="${CONFDIR%/}"
  555. PROFILE="${CONFDIR##*/}"
  556. CONF="$CONFDIR/conf"
  557. PRE="$CONFDIR/pre"
  558. POST="$CONFDIR/post"
  559. EXCLUDE="$CONFDIR/exclude"
  560. KEYFILE="$CONFDIR/gpgkey.asc"
  561. }
  562.  
  563. function version_info { # print version information
  564. cat <<END
  565.   $ME_NAME version $ME_VERSION
  566.   ($ME_WEBSITE)
  567. END
  568. }
  569.  
  570. function version_info_using {
  571. cat <<END
  572. $(version_info)
  573.  
  574.   $(using_info)
  575. END
  576. }
  577.  
  578. function using_info {
  579. # init needed vars into global name space
  580. lookup duplicity && { duplicity_python_binary_parse; duplicity_version_get; }
  581. local NOTFOUND="INVALID"
  582. local AWK_VERSION GREP_VERSION PYTHON_RUNNER
  583. # freebsd awk (--version only), debian mawk (-W version only), deliver '' so awk does not wait for input
  584. AWK_VERSION=$( lookup awk && (awk --version 2>/dev/null || awk -W version 2>&1) | awk 'NR<=2&&tolower($0)~/(busybox|awk)/{success=1;print;exit} END{if(success<1) print "unknown"}' || echo "$NOTFOUND" )
  585. GREP_VERSION=$( lookup grep && grep --version 2>&1 | awk 'NR<=2&&tolower($0)~/(busybox|grep.*[0-9]+\.[0-9]+)/{success=1;print;exit} END{if(success<1) print "unknown"}' || echo "$NOTFOUND" )
  586. PYTHON_RUNNER=$(python_binary)
  587. local PYTHON_VERSION=$(lookup "$PYTHON_RUNNER" && "$PYTHON_RUNNER" -V 2>&1| awk '{print tolower($0);exit}' || echo "'$PYTHON_RUNNER' $NOTFOUND" )
  588. local GPG_INFO=$(gpg_avail && gpg --version 2>&1| awk '/^gpg.*[0-9\.]+$/&&length(v)<1{v=$1" "$3}/^Home:/{h=" ("$0")"}END{print v""h}' || echo "gpg $NOTFOUND")
  589. local BASH_VERSION=$(bash --version | awk 'NR==1{IGNORECASE=1;sub(/GNU bash, version[ ]+/,"",$0);print $0}')
  590. # print out
  591. echo -e "Using installed duplicity version ${DUPL_VERSION:-$NOTFOUND}\
  592. ${PYTHON_VERSION+, $PYTHON_VERSION ${PYTHON_RUNNER:+($(which "$PYTHON_RUNNER"))}${PYTHONPATH:+ 'PYTHONPATH=$PYTHONPATH'}}\
  593. ${GPG_INFO:+, $GPG_INFO}${AWK_VERSION:+, awk '${AWK_VERSION}'}${GREP_VERSION:+, grep '${GREP_VERSION}'}\
  594. ${BASH_VERSION:+, bash '${BASH_VERSION}'}."
  595. }
  596.  
  597. function usage_info { # print usage information
  598.  
  599. cat <<USAGE_EOF
  600. VERSION:
  601. $(version_info)
  602.  
  603. DESCRIPTION:
  604. Duply deals as a wrapper for the mighty duplicity magic.
  605. It simplifies running duplicity with cron or on command line by:
  606.  
  607. - keeping recurring settings in profiles per backup job
  608. - enabling batch operations eg. backup_verify+purge
  609. - executing pre/post scripts (different actions possible
  610. depending on previous or next command or it's exit status)
  611. - precondition checking for flawless duplicity operation
  612.  
  613. For each backup job one configuration profile must be created.
  614. The profile folder will be stored under '~/.${ME_NAME}/<profile>'
  615. (where ~ is the current users home directory).
  616. Hint:
  617. If the folder '/etc/${ME_NAME}' exists, the profiles for the super
  618. user root will be searched & created there.
  619.  
  620. USAGE:
  621. first time usage (profile creation):
  622. $ME <profile> create
  623.  
  624. general usage in single or batch mode (see EXAMPLES):
  625. $ME <profile> <command>[[_|+|-]<command>[_|+|-]...] [<options> ...]
  626.  
  627. For batches the conditional separators can also be written as pseudo commands
  628. and(+), or(-). See SEPARATORS for details.
  629.  
  630. Non $ME options are passed on to duplicity (see OPTIONS).
  631. All conf parameters can also be defined in the environment instead.
  632.  
  633. PROFILE:
  634. Indicated by a path or a profile name (<profile>), which is resolved
  635. to '~/.${ME_NAME}/<profile>' (~ expands to environment variable \$HOME).
  636.  
  637. Superuser root can place profiles under '/etc/${ME_NAME}'. Simply create
  638. the folder manually before running $ME_NAME as superuser.
  639. Note:
  640. Already existing profiles in root's home folder will cease to work
  641. unless they are moved to the new location manually.
  642.  
  643. example 1: $ME humbug backup
  644.  
  645. Alternatively a _path_ might be used e.g. useful for quick testing,
  646. restoring or exotic locations. Shell expansion should work as usual.
  647. Hint:
  648. The path must contain at least one path separator '/',
  649. e.g. './test' instead of only 'test'.
  650.  
  651. example 2: $ME ~/.${ME_NAME}/humbug backup
  652.  
  653. SEPARATORS:
  654. _ (underscore)
  655. neutral separator
  656. + (plus sign), _and_
  657. conditional AND
  658. the next command will only be executed if the previous succeeded
  659. - (minus sign), _or_
  660. conditional OR
  661. the next command will only be executed if the previous failed
  662.  
  663. example:
  664. 'pre+bkp-verify_post' translates to 'pre_and_bkp_or_verify_post'
  665.  
  666. COMMANDS:
  667. usage get usage help text
  668.  
  669. and/or pseudo commands for better batch cmd readability (see SEPARATORS)
  670. create creates a configuration profile
  671. backup backup with pre/post script execution (batch: pre_bkp_post),
  672. full (if full_if_older matches or no earlier backup is found)
  673. incremental (in all other cases)
  674. pre/post execute '<profile>/$(basename "$PRE")', '<profile>/$(basename "$POST")' scripts
  675. bkp as above but without executing pre/post scripts
  676. full force full backup
  677. incr force incremental backup
  678. list [<age>]
  679. list all files in backup (as it was at <age>, default: now)
  680. status prints backup sets and chains currently in repository
  681. verify [<age>] [--compare-data]
  682. list files changed, since age if given
  683. verifyPath <rel_path_in_bkp> <local_path> [<age>] [--compare-data]
  684. list changes of a file or folder path in backup compared to a
  685. local path, since age if given
  686. restore <target_path> [<age>]
  687. restore the complete backup to <target_path> [as it was at <age>]
  688. fetch <src_path> <target_path> [<age>]
  689. fetch single file/folder from backup [as it was at <age>]
  690. purge [<max_age>] [--force]
  691. list outdated backup files (older than \$MAX_AGE)
  692. [use --force to actually delete these files]
  693. purgeFull [<max_full_backups>] [--force]
  694. list outdated backup files (\$MAX_FULL_BACKUPS being the number of
  695. full backups and associated incrementals to keep, counting in
  696. reverse chronological order)
  697. [use --force to actually delete these files]
  698. purgeIncr [<max_fulls_with_incrs>] [--force]
  699. list outdated incremental backups (\$MAX_FULLS_WITH_INCRS being
  700. the number of full backups which associated incrementals will be
  701. kept, counting in reverse chronological order)
  702. [use --force to actually delete these files]
  703. cleanup [--force]
  704. list broken backup chain files archives (e.g. after unfinished run)
  705. [use --force to actually delete these files]
  706.  
  707. changelog print changelog / todo list
  708. txt2man feature for package maintainers - create a manpage based on the
  709. usage output. download txt2man from http://mvertes.free.fr/, put
  710. it in the PATH and run '$ME txt2man' to create a man page.
  711. version show version information of $ME_NAME and needed programs
  712.  
  713. OPTIONS:
  714. --force passed to duplicity (see commands:
  715. purge, purgeFull, purgeIncr, cleanup)
  716. --preview do nothing but print out generated duplicity command lines
  717. --disable-encryption
  718. disable encryption, overrides profile settings
  719.  
  720. TIME FORMATS:
  721. For all time related parameters like age, max_age etc.
  722. Refer to the duplicity manpage for all available formats. Here some examples:
  723. 2002-01-25T07:00:00+02:00 (full date time format string)
  724. 2002/3/5 (date string YYYY/MM/DD)
  725. 12D (interval, 12 days ago)
  726. 1h78m (interval, 1 hour 78 minutes ago)
  727.  
  728. PRE/POST SCRIPTS:
  729. Some useful internal duply variables are exported to the scripts.
  730.  
  731. PROFILE, CONFDIR, SOURCE, TARGET_URL_<PROT|HOSTPATH|USER|PASS>,
  732. GPG_<KEYS_ENC|KEY_SIGN|PW>, CMD_<PREV|NEXT>, CMD_ERR, RUN_START,
  733. CND_<PREV|NEXT> (condition before/after next/prev command)
  734.  
  735. The CMD_* variables were introduced to allow different actions according to
  736. the command the scripts were attached to e.g. 'pre_bkp_post_pre_verify_post'
  737. will call the pre script two times, with CMD_NEXT variable set to 'bkp'
  738. on the first and to 'verify' on the second run.
  739. CMD_ERR holds the exit code of the CMD_PREV .
  740.  
  741. EXAMPLES:
  742. create profile 'humbug':
  743. $ME humbug create (don't forget to edit this new conf file)
  744. backup 'humbug' now:
  745. $ME humbug backup
  746. list available backup sets of profile 'humbug':
  747. $ME humbug status
  748. list and delete outdated backups of 'humbug':
  749. $ME humbug purge --force
  750. restore latest backup of 'humbug' to /mnt/restore:
  751. $ME humbug restore /mnt/restore
  752. restore /etc/passwd of 'humbug' from 4 days ago to /root/pw:
  753. $ME humbug fetch etc/passwd /root/pw 4D
  754. (see "duplicity manpage", section TIME FORMATS)
  755. a one line batch job on 'humbug' for cron execution:
  756. $ME humbug backup_verify_purge --force
  757. batch job to run a full backup with pre/post scripts:
  758. $ME humbug pre_full_post
  759.  
  760. FILES:
  761. in profile folder '~/.${ME_NAME}/<profile>' or '/etc/${ME_NAME}'
  762. conf profile configuration file
  763. pre,post pre/post scripts (see above for details)
  764. gpgkey.*.asc exported GPG key files
  765. exclude a globbing list of included or excluded files/folders
  766. (see "duplicity manpage", section FILE SELECTION)
  767.  
  768. $(hint_profile)
  769.  
  770. SEE ALSO:
  771. duplicity man page:
  772. duplicity(1) or http://duplicity.nongnu.org/duplicity.1.html
  773. USAGE_EOF
  774. }
  775.  
  776. # to check call 'duply txt2man | man -l -'
  777. function usage_txt2man {
  778. usage_info | \
  779. awk '/^^[^[:lower:][:space:]][^[:lower:]]+$/{gsub(/[^[:upper:]]/," ",$0)}{print}' |\
  780. txt2man -t"$(toupper "${ME_NAME}")" -s1 -r"${ME_NAME}-${ME_VERSION}" -v'User Manuals'
  781. }
  782.  
  783. function changelog {
  784. cat $ME_LONG | awk '/^#####/{on=on+1}(on==3){sub(/^#( )?/,"",$0);print}'
  785. }
  786.  
  787. function create_config {
  788. if [ ! -d "$CONFDIR" ] ; then
  789. mkdir -p "$CONFDIR" || error "Couldn't create config '$CONFDIR'."
  790. # create initial config file
  791. cat <<EOF >"$CONF"
  792. # gpg encryption settings, simple settings:
  793. # GPG_KEY='disabled' - disables encryption alltogether
  794. # GPG_KEY='<key1>[,<key2>]'; GPG_PW='pass' - encrypt with keys,
  795. # sign if secret key of key1 is available use GPG_PW for sign & decrypt
  796. # Note: you can specify keys via all methods described in gpg manpage,
  797. # section "How to specify a user ID", escape commas (,) via backslash (\)
  798. # e.g. 'Mueller, Horst', 'Bernd' -> 'Mueller\, Horst, Bernd'
  799. # as they are used to separate the entries
  800. # GPG_PW='passphrase' - symmetric encryption using passphrase only
  801. GPG_KEY='${DEFAULT_GPG_KEY}'
  802. GPG_PW='${DEFAULT_GPG_PW}'
  803. # gpg encryption settings in detail (extended settings)
  804. # the above settings translate to the following more specific settings
  805. # GPG_KEYS_ENC='<keyid1>[,<keyid2>,...]' - list of pubkeys to encrypt to
  806. # GPG_KEY_SIGN='<keyid1>|disabled' - a secret key for signing
  807. # GPG_PW='<passphrase>' - needed for signing, decryption and symmetric
  808. # encryption. If you want to deliver different passphrases for e.g.
  809. # several keys or symmetric encryption plus key signing you can use
  810. # gpg-agent. Simply make sure that GPG_AGENT_INFO is set in environment.
  811. # also see "A NOTE ON SYMMETRIC ENCRYPTION AND SIGNING" in duplicity manpage
  812. # notes on en/decryption
  813. # private key and passphrase will only be needed for decryption or signing.
  814. # decryption happens on restore and incrementals (compare archdir contents).
  815. # for security reasons it makes sense to separate the signing key from the
  816. # encryption keys. https://answers.launchpad.net/duplicity/+question/107216
  817. #GPG_KEYS_ENC='<pubkey1>,<pubkey2>,...'
  818. #GPG_KEY_SIGN='<prvkey>'
  819. # set if signing key passphrase differs from encryption (key) passphrase
  820. # NOTE: available since duplicity 0.6.14, translates to SIGN_PASSPHRASE
  821. #GPG_PW_SIGN='<signpass>'
  822.  
  823. # uncomment and set a file path or name force duply to use this gpg executable
  824. # available in duplicity 0.7.04 and above (currently unreleased 06/2015)
  825. #GPG='/usr/local/gpg-2.1/bin/gpg'
  826.  
  827. # gpg options passed from duplicity to gpg process (default='')
  828. # e.g. "--trust-model pgp|classic|direct|always"
  829. # or "--compress-algo=bzip2 --bzip2-compress-level=9"
  830. # or "--personal-cipher-preferences AES256,AES192,AES..."
  831. # or "--homedir ~/.duply" - keep keyring and gpg settings duply specific
  832. # or "--pinentry-mode loopback" - needed for GPG 2.1+ _and_
  833. # also enable allow-loopback-pinentry in your .gnupg/gpg-agent.conf
  834. #GPG_OPTS=''
  835.  
  836. # disable preliminary tests with the following setting
  837. #GPG_TEST='disabled'
  838.  
  839. # backend, credentials & location of the backup target (URL-Format)
  840. # generic syntax is
  841. # scheme://[user[:password]@]host[:port]/[/]path
  842. # eg.
  843. # sftp://bob:secret@backupserver.com//home/bob/dupbkp
  844. # for details and available backends see duplicity manpage, section URL Format
  845. # http://duplicity.nongnu.org/duplicity.1.html#sect7
  846. # BE AWARE:
  847. # some backends (cloudfiles, S3 etc.) need additional env vars to be set to
  848. # work properly, read after the TARGET definition for more details.
  849. # ATTENTION:
  850. # characters other than A-Za-z0-9.-_.~ in the URL have to be
  851. # replaced by their url encoded pendants, see
  852. # http://en.wikipedia.org/wiki/Url_encoding
  853. # if you define the credentials as TARGET_USER, TARGET_PASS below $ME
  854. # will try to url_encode them for you if the need arises.
  855. TARGET='${DEFAULT_TARGET}'
  856. # optionally the username/password can be defined as extra variables
  857. # setting them here _and_ in TARGET results in an error
  858. # ATTENTION:
  859. # there are backends that do not support the user/pass auth scheme.
  860. # prominent examples are S3, Azure, Cloudfiles. when in doubt consult the
  861. # duplicity manpage. usually there is a NOTE section explaining if and which
  862. # env vars should be set.
  863. #TARGET_USER='${DEFAULT_TARGET_USER}'
  864. #TARGET_PASS='${DEFAULT_TARGET_PASS}'
  865. # eg. for cloud files backend it might look like this (uncomment for use!)
  866. #export CLOUDFILES_USERNAME='someuser'
  867. #export CLOUDFILES_APIKEY='somekey'
  868. #export CLOUDFILES_AUTHURL ='someurl'
  869. # the following is an incomplete list (<backend>: comma separated env vars list)
  870. # Azure: AZURE_ACCOUNT_NAME, AZURE_ACCOUNT_KEY
  871. # Cloudfiles: CLOUDFILES_USERNAME, CLOUDFILES_APIKEY, CLOUDFILES_AUTHURL
  872. # Google Cloud Storage: GS_ACCESS_KEY_ID, GS_SECRET_ACCESS_KEY
  873. # Pydrive: GOOGLE_DRIVE_ACCOUNT_KEY, GOOGLE_DRIVE_SETTINGS
  874. # S3: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
  875. # Swift: SWIFT_USERNAME, SWIFT_PASSWORD, SWIFT_AUTHURL,
  876. # SWIFT_TENANTNAME OR SWIFT_PREAUTHURL, SWIFT_PREAUTHTOKEN
  877.  
  878. # base directory to backup
  879. SOURCE='${DEFAULT_SOURCE}'
  880.  
  881. # a command that runs duplicity e.g.
  882. # shape bandwidth use via trickle
  883. # "trickle -s -u 640 -d 5120" # 5Mb up, 40Mb down"
  884. #DUPL_PRECMD=""
  885.  
  886. # override the used python interpreter, defaults to
  887. # - parsed result of duplicity's shebang or 'python2'
  888. # e.g. "python2" or "/usr/bin/python2.7"
  889. #PYTHON="python"
  890.  
  891. # exclude folders containing exclusion file (since duplicity 0.5.14)
  892. # Uncomment the following two lines to enable this setting.
  893. #FILENAME='.duplicity-ignore'
  894. #DUPL_PARAMS="\$DUPL_PARAMS --exclude-if-present '\$FILENAME'"
  895.  
  896. # Time frame for old backups to keep, Used for the "purge" command.
  897. # see duplicity man page, chapter TIME_FORMATS)
  898. #MAX_AGE=1M
  899.  
  900. # Number of full backups to keep. Used for the "purgeFull" command.
  901. # See duplicity man page, action "remove-all-but-n-full".
  902. #MAX_FULL_BACKUPS=1
  903.  
  904. # Number of full backups for which incrementals will be kept for.
  905. # Used for the "purgeIncr" command.
  906. # See duplicity man page, action "remove-all-inc-of-but-n-full".
  907. #MAX_FULLS_WITH_INCRS=1
  908.  
  909. # activates duplicity --full-if-older-than option (since duplicity v0.4.4.RC3)
  910. # forces a full backup if last full backup reaches a specified age, for the
  911. # format of MAX_FULLBKP_AGE see duplicity man page, chapter TIME_FORMATS
  912. # Uncomment the following two lines to enable this setting.
  913. #MAX_FULLBKP_AGE=1M
  914. #DUPL_PARAMS="\$DUPL_PARAMS --full-if-older-than \$MAX_FULLBKP_AGE "
  915.  
  916. # sets duplicity --volsize option (available since v0.4.3.RC7)
  917. # set the size of backup chunks to VOLSIZE MB instead of the default 25MB.
  918. # VOLSIZE must be number of MB's to set the volume size to.
  919. # Uncomment the following two lines to enable this setting.
  920. #VOLSIZE=50
  921. #DUPL_PARAMS="\$DUPL_PARAMS --volsize \$VOLSIZE "
  922.  
  923. # verbosity of output (error 0, warning 1-2, notice 3-4, info 5-8, debug 9)
  924. # default is 4, if not set
  925. #VERBOSITY=5
  926.  
  927. # temporary file space. at least the size of the biggest file in backup
  928. # for a successful restoration process. (default is '/tmp', if not set)
  929. #TEMP_DIR=/tmp
  930.  
  931. # Modifies archive-dir option (since 0.6.0) Defines a folder that holds
  932. # unencrypted meta data of the backup, enabling new incrementals without the
  933. # need to decrypt backend metadata first. If empty or deleted somehow, the
  934. # private key and it's password are needed.
  935. # NOTE: This is confidential data. Put it somewhere safe. It can grow quite
  936. # big over time so you might want to put it not in the home dir.
  937. # default '~/.cache/duplicity/duply_<profile>/'
  938. # if set '\${ARCH_DIR}/<profile>'
  939. #ARCH_DIR=/some/space/safe/.duply-cache
  940.  
  941. # DEPRECATED setting
  942. # sets duplicity --time-separator option (since v0.4.4.RC2) to allow users
  943. # to change the time separator from ':' to another character that will work
  944. # on their system. HINT: For Windows SMB shares, use --time-separator='_'.
  945. # NOTE: '-' is not valid as it conflicts with date separator.
  946. # ATTENTION: only use this with duplicity < 0.5.10, since then default file
  947. # naming is compatible and this option is pending depreciation
  948. #DUPL_PARAMS="\$DUPL_PARAMS --time-separator _ "
  949.  
  950. # DEPRECATED setting
  951. # activates duplicity --short-filenames option, when uploading to a file
  952. # system that can't have filenames longer than 30 characters (e.g. Mac OS 8)
  953. # or have problems with ':' as part of the filename (e.g. Microsoft Windows)
  954. # ATTENTION: only use this with duplicity < 0.5.10, later versions default file
  955. # naming is compatible and this option is pending depreciation
  956. #DUPL_PARAMS="\$DUPL_PARAMS --short-filenames "
  957.  
  958. # more duplicity command line options can be added in the following way
  959. # don't forget to leave a separating space char at the end
  960. #DUPL_PARAMS="\$DUPL_PARAMS --put_your_options_here "
  961.  
  962. EOF
  963.  
  964. # create initial exclude file
  965. cat <<EOF >"$EXCLUDE"
  966. # although called exclude, this file is actually a globbing file list
  967. # duplicity accepts some globbing patterns, even including ones here
  968. # here is an example, this incl. only 'dir/bar' except it's subfolder 'foo'
  969. # - dir/bar/foo
  970. # + dir/bar
  971. # - **
  972. # for more details see duplicity manpage, section File Selection
  973. # http://duplicity.nongnu.org/duplicity.1.html#sect9
  974.  
  975. EOF
  976.  
  977. # Hints on first usage
  978. cat <<EOF
  979.  
  980. Congratulations. You just created the profile '$FTPLCFG'.
  981. The initial config file has been created as
  982. '$CONF'.
  983. You should now adjust this config file to your needs.
  984.  
  985. $(hint_profile)
  986.  
  987. EOF
  988. fi
  989.  
  990. }
  991.  
  992. # used in usage AND create_config
  993. function hint_profile {
  994. cat <<EOF
  995. IMPORTANT:
  996.   Copy the _whole_ profile folder after the first backup to a safe place.
  997.   It contains everything needed to restore your backups. You will need
  998.   it if you have to restore the backup from another system (e.g. after a
  999.   system crash). Keep access to these files restricted as they contain
  1000.   _all_ informations (gpg data, ftp data) to access and modify your backups.
  1001.  
  1002.   Repeat this step after _all_ configuration changes. Some configuration
  1003.   options are crucial for restoration.
  1004.  
  1005. EOF
  1006. }
  1007.  
  1008. function separator {
  1009. echo "--- $@ ---"
  1010. }
  1011.  
  1012. function inform {
  1013. echo -e "\nINFO:\n\n$@\n"
  1014. }
  1015.  
  1016. function warning {
  1017. echo -e "\nWARNING:\n\n$@\n"
  1018. }
  1019.  
  1020. function warning_oldhome {
  1021. local old=$1 new=$2
  1022. warning " ftplicity changed name to duply since you created your profiles.
  1023. Please rename the old folder
  1024. '$old'
  1025. to
  1026. '$new'
  1027. and this warning will disappear.
  1028. If you decide not to do so profiles will _only_ work from the old location."
  1029. }
  1030.  
  1031. function error_print {
  1032. echo -e "$@" >&2
  1033. }
  1034.  
  1035. function error {
  1036. error_print "\nSorry. A fatal ERROR occured:\n\n$@\n"
  1037. exit -1
  1038. }
  1039.  
  1040. function error_gpg {
  1041. [ -n "$2" ] && local hint="\n $2\n\n "
  1042.  
  1043. error "$1
  1044.  
  1045. Hint${hint:+s}:
  1046. ${hint}Maybe you have not created a gpg key yet (e.g. gpg --gen-key)?
  1047. Don't forget the used _password_ as you will need it.
  1048. When done enter the 8 digit id & the password in the profile conf file.
  1049.  
  1050. The key id can be found doing a 'gpg --list-keys'. In the example output
  1051. below the key id would be FFFFFFFF for the public key.
  1052.  
  1053. pub 1024D/FFFFFFFF 2007-12-17
  1054. uid duplicity
  1055. sub 2048g/899FE27F 2007-12-17
  1056. "
  1057. }
  1058.  
  1059. function error_gpg_key {
  1060. local KEY_ID="$1"
  1061. local KIND="$2"
  1062. error_gpg "${KIND} gpg key '${KEY_ID}' cannot be found." \
  1063. "Doublecheck if the above key is listed by 'gpg --list-keys' or available
  1064. as gpg key file '$(basename "$(gpg_keyfile "${KEY_ID}")")' in the profile folder.
  1065. If not you can put it there and $ME_NAME will autoimport it on the next run.
  1066. Alternatively import it manually as the user you plan to run $ME_NAME with."
  1067. }
  1068.  
  1069. function error_gpg_test {
  1070. [ -n "$2" ] && local hint="\n $2\n\n "
  1071.  
  1072. error "$1
  1073.  
  1074. Hint${hint:+s}:
  1075. ${hint}This error means that gpg is probably misconfigured or not working
  1076. correctly. The error message above should help to solve the problem.
  1077. However, if for some reason $ME_NAME should misinterpret the situation you
  1078. can define GPG_TEST='disabled' in the conf file to bypass the test.
  1079. Please do not forget to report the bug in order to resolve the problem
  1080. in future versions of $ME_NAME.
  1081. "
  1082. }
  1083.  
  1084. function error_path {
  1085. error "$@
  1086. PATH='$PATH'
  1087. "
  1088. }
  1089.  
  1090. function error_to_string {
  1091. [ -n "$1" ] && [ "$1" -eq 0 ] && echo "OK" || echo "FAILED 'code $1'"
  1092. }
  1093.  
  1094. function duplicity_version_get {
  1095. # nothing to do, just print
  1096. var_isset DUPL_VERSION && return
  1097.  
  1098. local DUPL_VERSION_OUT DUPL_VERSION_AWK PYTHON_BIN CMD='duplicity'
  1099. # only run with a user specific python if configured (running by default
  1100. # breaks homebrew as they place a shell wrapper for duplicity in path)
  1101. PYTHON_BIN="$(python_binary)" &&\
  1102. CMD="$(qw "$PYTHON_BIN") $(which $CMD)"
  1103. CMD="$CMD --version 2>&1"
  1104. DUPL_VERSION_OUT=$(eval "$CMD")
  1105. DUPL_VERSION=`echo $DUPL_VERSION_OUT | awk '/^duplicity /{print $2; exit;}'`
  1106. #DUPL_VERSION='0.7.03' #'0.6.08b' #,0.4.4.RC4,0.6.08b
  1107. DUPL_VERSION_VALUE=0
  1108. DUPL_VERSION_AWK=$(awk -v v="$DUPL_VERSION" 'BEGIN{
  1109. if (match(v,/[^\.0-9]+[0-9]*$/)){
  1110. rest=substr(v,RSTART,RLENGTH);v=substr(v,0,RSTART-1);}
  1111. if (pos=match(rest,/RC([0-9]+)$/)) rc=substr(rest,pos+2)
  1112. split(v,f,"[. ]"); if(f[1]f[2]f[3]~/^[0-9]+$/) vvalue=f[1]*10000+f[2]*100+f[3]; else vvalue=0
  1113. print "#"v"_"rest"("rc"):"f[1]"-"f[2]"-"f[3]
  1114. print "DUPL_VERSION_VALUE=\047"vvalue"\047"
  1115. print "DUPL_VERSION_RC=\047"rc"\047"
  1116. print "DUPL_VERSION_SUFFIX=\047"rest"\047"
  1117. }')
  1118. eval "$DUPL_VERSION_AWK"
  1119. #echo -e ",$DUPL_VERSION,$DUPL_VERSION_VALUE,$DUPL_VERSION_RC,$DUPL_VERSION_SUFFIX,"
  1120.  
  1121. # doublecheck findings and report error
  1122. if [ $DUPL_VERSION_VALUE -eq 0 ]; then
  1123. inform "duplicity version check failed (please report, this is a bug)
  1124. the command
  1125. $CMD
  1126. resulted in
  1127. $DUPL_VERSION_OUT
  1128. "
  1129. elif [ $DUPL_VERSION_VALUE -le 404 ] && [ ${DUPL_VERSION_RC:-4} -lt 4 ]; then
  1130. error "The installed version $DUPL_VERSION is incompatible with $ME_NAME v$ME_VERSION.
  1131. You should upgrade your version of duplicity to at least v0.4.4RC4 or
  1132. use the older ftplicity version 1.1.1 from $ME_WEBSITE."
  1133. fi
  1134. }
  1135.  
  1136. function duplicity_version_ge {
  1137. [ "$DUPL_VERSION_VALUE" -ge "$1" ]
  1138. }
  1139.  
  1140. function duplicity_version_lt {
  1141.  ! duplicity_version_ge "$1"
  1142. }
  1143.  
  1144. # parse interpreter from duplicity shebang
  1145. function duplicity_python_binary_parse {
  1146. # cached result
  1147. ( var_isset 'PYTHON' || var_isset 'DUPL_PYTHON_BIN' ) && return
  1148.  
  1149. # parse it or warn
  1150. local DUPL_BIN=$(which duplicity)
  1151. DUPL_PYTHON_BIN=$(awk 'NR==1&&/^#!/{sub(/^#!( *\/usr\/bin\/env *)?/,""); print}' < "$DUPL_BIN")
  1152. if ! echo "$DUPL_PYTHON_BIN" | grep -q -i 'python'; then
  1153. warning "Could not parse the python interpreter used from duplicity ($DUPL_BIN). Result was '$DUPL_PYTHON_BIN'.
  1154. Will assume it is '$DEFAULT_PYTHON'."
  1155. DUPL_PYTHON_BIN="$DEFAULT_PYTHON"
  1156. fi
  1157. }
  1158.  
  1159. function run_script { # run pre/post scripts
  1160. local ERR=0
  1161. local SCRIPT="$1"
  1162. if [ ! -z "$PREVIEW" ] ; then
  1163. echo "$([ ! -x "$SCRIPT" ] && echo ". ")$SCRIPT"
  1164. elif [ -r "$SCRIPT" ] ; then
  1165. echo -n "Running '$SCRIPT' "
  1166. if [ -x "$SCRIPT" ]; then
  1167. OUT=$("$SCRIPT" 2>&1)
  1168. ERR=$?
  1169. else
  1170. OUT=$(. "$SCRIPT" 2>&1)
  1171. ERR=$?
  1172. fi
  1173. [ $ERR -eq "0" ] && echo "- OK" || echo "- FAILED (code $ERR)"
  1174. echo -en ${OUT:+"Output: $OUT\n"} ;
  1175. else
  1176. echo "Skipping n/a script '$SCRIPT'."
  1177. fi
  1178. return $ERR
  1179. }
  1180.  
  1181. function run_cmd {
  1182. # run or print escaped cmd string
  1183. local CMD_ERR=0
  1184. if [ -n "$PREVIEW" ]; then
  1185. CMD_OUT=$( echo "$@ 2>&1" )
  1186. CMD_MSG="-- Run cmd -- $CMD_MSG --\n$CMD_OUT"
  1187. elif [ -n "$CMD_DISABLED" ]; then
  1188. CMD_MSG="$CMD_MSG (DISABLED) - $CMD_DISABLED"
  1189. else
  1190. echo -n -e "$CMD_MSG"
  1191. CMD_OUT=` eval "$@" 2>&1 `
  1192. CMD_ERR=$?
  1193. if [ "$CMD_ERR" = "0" ]; then
  1194. CMD_MSG=" (OK)"
  1195. else
  1196. CMD_MSG=" (FAILED)"
  1197. fi
  1198. fi
  1199. echo -e "$CMD_MSG"
  1200. # reset
  1201. unset CMD_DISABLED CMD_MSG
  1202. return $CMD_ERR
  1203. }
  1204.  
  1205. function qw { quotewrap "$@"; }
  1206.  
  1207. function quotewrap {
  1208. local param="$@"
  1209. # quote strings having non word chars (e.g. spaces)
  1210. if echo "$param" | awk '/[^A-Za-z0-9_\.\-\/]/{exit 0}{exit 1}'; then
  1211. echo "$param" | awk '{\
  1212. gsub(/[\047]/,"\047\\\047\047",$0);\
  1213. gsub(/[\042]/,"\047\\\042\047",$0);\
  1214. print "\047"$0"\047"}'
  1215. return
  1216. fi
  1217. echo $param
  1218. }
  1219.  
  1220. function duplicity_params_global {
  1221. # already done? return
  1222. var_isset 'DUPL_PARAMS_GLOBAL' && return
  1223. local DUPL_ARG_ENC
  1224.  
  1225. # use key only if set in config, else leave it to symmetric encryption
  1226. if gpg_disabled; then
  1227. local DUPL_PARAM_ENC='--no-encryption'
  1228. else
  1229. local DUPL_PARAM_ENC=$(gpg_prefix_keyset '--encrypt-key' "${GPG_KEYS_ENC_ARRAY[@]}")
  1230. gpg_signing && local DUPL_PARAM_SIGN=$(gpg_prefix_keyset '--sign-key' "$GPG_KEY_SIGN")
  1231. # interpret password settings
  1232. var_isset 'GPG_PW' && DUPL_ARG_ENC="PASSPHRASE=$(qw "${GPG_PW}")"
  1233. var_isset 'GPG_PW_SIGN' && DUPL_ARG_ENC="${DUPL_ARG_ENC} SIGN_PASSPHRASE=$(qw "${GPG_PW_SIGN}")"
  1234. fi
  1235.  
  1236. local GPG_OPTS=${GPG_OPTS:+"--gpg-options $(qw "${GPG_OPTS}")"}
  1237.  
  1238. # set name for dupl archive folder, since 0.6.0
  1239. if duplicity_version_ge 601; then
  1240. local DUPL_ARCHDIR=''
  1241. if var_isset 'ARCH_DIR'; then
  1242. DUPL_ARCHDIR="--archive-dir $(qw "${ARCH_DIR}")"
  1243. # reuse erronously duply_ prefixed folders from bug #117
  1244. if [ -d "$ARCH_DIR/duply_${PROFILE}" ]; then
  1245. DUPL_ARCHDIR="${DUPL_ARCHDIR} --name $(qw "duply_${PROFILE}")"
  1246. else
  1247. DUPL_ARCHDIR="${DUPL_ARCHDIR} --name $(qw "${PROFILE}")"
  1248. fi
  1249. else
  1250. DUPL_ARCHDIR="--name $(qw "duply_${PROFILE}")"
  1251. fi
  1252. fi
  1253.  
  1254. DUPL_PARAMS_GLOBAL="${DUPL_ARCHDIR} ${DUPL_PARAM_ENC} \
  1255. ${DUPL_PARAM_SIGN} --verbosity '${VERBOSITY:-4}' \
  1256. ${GPG_OPTS}"
  1257.  
  1258. DUPL_VARS_GLOBAL="TMPDIR='$TEMP_DIR' \
  1259. ${DUPL_ARG_ENC}"
  1260. }
  1261.  
  1262.  
  1263. # function to filter the DUPL_PARAMS var from user conf
  1264. function duplicity_params_conf {
  1265. # reuse cmd var from main loop
  1266. ## in/exclude parameters are currently not supported on restores
  1267. if [ "$cmd" = "fetch" ] || [ "$cmd" = "restore" ] || [ "$cmd" = "status" ]; then
  1268. # filter exclude params from fetch/restore
  1269. echo "$DUPL_PARAMS" | awk '{gsub(/--(ex|in)clude[a-z-]*(([ \t]+|=)[^-][^ \t]+)?/,"");print}'
  1270. return
  1271. fi
  1272.  
  1273. echo "$DUPL_PARAMS"
  1274. }
  1275.  
  1276. function duplify { # the actual wrapper function
  1277. local PARAMSNOW DUPL_CMD DUPL_CMD_PARAMS
  1278.  
  1279. # put command (with params) first in duplicity parameters
  1280. for param in "$@" ; do
  1281. # split cmd from params (everything before splitchar --)
  1282. if [ "$param" == "--" ] ; then
  1283. PARAMSNOW=1
  1284. else
  1285. # wrap in quotes to protect from spaces
  1286. [ ! $PARAMSNOW ] && \
  1287. DUPL_CMD="$DUPL_CMD $(qw "$param")" \
  1288. || \
  1289. DUPL_CMD_PARAMS="$DUPL_CMD_PARAMS $(qw "$param")"
  1290. fi
  1291. done
  1292.  
  1293. # init global duplicity parameters same for all tasks
  1294. duplicity_params_global
  1295.  
  1296. local RUN=eval BIN=duplicity DUPL_BIN PYTHON_BIN
  1297. # run in cmd line preview mode if requested
  1298. var_isset 'PREVIEW' && RUN=echo
  1299. # try to resolve duplicity path for usage with python interpreter
  1300. DUPL_BIN=$(which "$BIN") || DUPL_BIN="$BIN"
  1301. # only run with a user specific python if configured (running by default
  1302. # breaks homebrew as they place a shell wrapper for duplicity in path)
  1303. PYTHON_BIN="$(python_binary)" &&\
  1304. BIN="$(qw "$PYTHON_BIN") $(qw "$DUPL_BIN")"
  1305.  
  1306. $RUN "${DUPL_VARS_GLOBAL} ${BACKEND_PARAMS}\
  1307. ${DUPL_PRECMD} $BIN $DUPL_CMD $DUPL_PARAMS_GLOBAL $(duplicity_params_conf)\
  1308. $GPG_USEAGENT $(gpg_custom_binary) $DUPL_CMD_PARAMS"
  1309.  
  1310. local ERR=$?
  1311. return $ERR
  1312. }
  1313.  
  1314. function secureconf { # secure the configuration dir
  1315. #PERMS=$(ls -la $(dirname $CONFDIR) | grep -e " $(basename $CONFDIR)\$" | awk '{print $1}')
  1316. local PERMS="$(ls -la "$CONFDIR/." | awk 'NR==2{print $1}')"
  1317. if [ "${PERMS/#drwx------*/OK}" != 'OK' ] ; then
  1318. chmod u+rwX,go= "$CONFDIR"; local ERR=$?
  1319. warning "The profile's folder
  1320. '$CONFDIR'
  1321. permissions are not safe ($PERMS). Secure them now. - ($(error_to_string $ERR))"
  1322. fi
  1323. }
  1324.  
  1325. # params are $1=timeformatstring (default like date output), $2=epoch seconds since 1.1.1970 (default now)
  1326. function date_fix {
  1327. local DEFAULTFORMAT='%a %b %d %H:%M:%S %Z %Y'
  1328. local date
  1329. #[ "$1" == "%N" ] && return #test the no nsec test below
  1330. # gnu date with -d @epoch
  1331. date=$(date ${2:+-d @$2} ${1:++"$1"} 2> /dev/null) && \
  1332. echo $date && return
  1333. # date bsd,osx with -r epoch
  1334. date=$(date ${2:+-r $2} ${1:++"$1"} 2> /dev/null) && \
  1335. echo $date && return
  1336. # date busybox with -d epoch -D %s
  1337. date=$(date ${2:+-d $2 -D %s} ${1:++"$1"} 2> /dev/null) && \
  1338. echo $date && return
  1339. ## some date commands do not support giving a time w/o setting it systemwide (irix,solaris,others?)
  1340. # python fallback
  1341. date=$("$(python_binary)" -c "import time;print time.strftime('${1:-$DEFAULTFORMAT}',time.localtime(${2}))" 2> /dev/null) && \
  1342. echo $date && return
  1343. # awk fallback
  1344. date=$(awk "BEGIN{print strftime(\"${1:-$DEFAULTFORMAT}\"${2:+,$2})}" 2> /dev/null) && \
  1345. echo $date && return
  1346. # perl fallback
  1347. date=$(perl -e "use POSIX qw(strftime);\$date = strftime(\"${1:-$DEFAULTFORMAT}\",localtime(${2}));print \"\$date\n\";" 2> /dev/null) && \
  1348. echo $date && return
  1349. # error
  1350. echo "ERROR"
  1351. return 1
  1352. }
  1353.  
  1354. function nsecs {
  1355. local NSECS
  1356. # test if date supports nanosecond output
  1357. if ! var_isset NSECS_DISABLED; then
  1358. NSECS=$(date_fix %N 2> /dev/null | head -1 |grep -e "^[[:digit:]]\{9\}$")
  1359. [ -n "$NSECS" ] && NSECS_DISABLED=0 || NSECS_DISABLED=1
  1360. fi
  1361.  
  1362. # add 9 digits, not all date(s) deliver nsecs eg. busybox date
  1363. if [ "$NSECS_DISABLED" == "1" ]; then
  1364. date_fix %s000000000
  1365. else
  1366. date_fix %s%N
  1367. fi
  1368. }
  1369.  
  1370. function nsecs_to_sec {
  1371. echo $(($1/1000000000)).$(printf "%03d" $(($1/1000000%1000)) )
  1372. }
  1373.  
  1374. function datefull_from_nsecs {
  1375. date_from_nsecs $1 '%F %T'
  1376. }
  1377.  
  1378. function date_from_nsecs {
  1379. local FORMAT=${2:-%T}
  1380. local TIME=$(nsecs_to_sec $1)
  1381. local SECS=${TIME%.*}
  1382. local DATE=$(date_fix "%T" ${SECS:-0})
  1383. echo $DATE.${TIME#*.}
  1384. }
  1385.  
  1386. function var_isset {
  1387. if [ -z "$1" ]; then
  1388. echo "ERROR: function var_isset needs a string as parameter"
  1389. elif eval "[ \"\${$1}\" == 'not_set' ]" || eval "[ \"\${$1-not_set}\" != 'not_set' ]"; then
  1390. return 0
  1391. fi
  1392. return 1
  1393. }
  1394.  
  1395. function is_condition {
  1396. local CMD=$(tolower "$@")
  1397. [ "$CMD" == 'and' ] || [ "$CMD" == 'or' ]
  1398. }
  1399.  
  1400. function url_encode {
  1401. # utilize python, silently do nothing on error - because no python no duplicity
  1402. OUT=$("$(python_binary)" -c "
  1403. try: import urllib.request as urllib
  1404. except ImportError: import urllib
  1405. print(urllib.${2}quote('$1'));
  1406. " 2>/dev/null ); ERR=$?
  1407. [ "$ERR" -eq 0 ] && echo $OUT || echo $1
  1408. }
  1409.  
  1410. function url_decode {
  1411. # reuse function above with a simple string param hack
  1412. url_encode "$1" "un"
  1413. }
  1414.  
  1415. function toupper {
  1416. echo "$@"|awk '$0=toupper($0)'
  1417. }
  1418.  
  1419. function tolower {
  1420. echo "$@"|awk '$0=tolower($0)'
  1421. }
  1422.  
  1423. function isnumber {
  1424. case "$*" in
  1425. ''|*[!0-9]*) return 1;;
  1426. *) return 0;;
  1427. esac
  1428. }
  1429.  
  1430. #function tmp_space {
  1431. #
  1432. # if ! isnumber $VOLSIZE; then
  1433. # inform "failed to determine free space (please report, this is a bug)"
  1434. # return
  1435. # fi
  1436. #
  1437. # get free temp space
  1438. # TEMP_FREE="$(df -P -k "$TEMP_DIR" 2>/dev/null | awk 'END{pos=(NF-2);if(pos>0) print $pos;}')"
  1439. # # check for free space or FAIL
  1440. # if [ $((${TEMP_FREE:-0}-${VOLSIZE:-0}*1024)) -lt 0-lt 0 ]; then
  1441. # error "Temporary file space '$TEMP_DIR' free space is smaller ($((TEMP_FREE/1024))MB)
  1442. #than one duplicity volume (${VOLSIZE}MB).
  1443. #
  1444. # Hint: Free space or change TEMP_DIR setting."
  1445. #fi
  1446. #
  1447. #}
  1448.  
  1449. function gpg_disabled {
  1450. echo "${GPG_KEY}" | grep -iq -e '^disabled$'
  1451. }
  1452.  
  1453. # usage: join SEPARATOR "entry1" "entry2"
  1454. function join {
  1455. local SEP="$1" ENTRY OUT; shift;
  1456. for ENTRY in "$@"; do
  1457. ENTRY=${ENTRY//$SEP/\\$SEP}
  1458. [ -z "$OUT" ] && OUT=$ENTRY || OUT="$OUT$SEP$ENTRY"
  1459. done
  1460. echo $OUT
  1461. }
  1462.  
  1463. function gpg_signing {
  1464. echo ${GPG_KEY_SIGN} | grep -v -q -e '^disabled$'
  1465. }
  1466.  
  1467. # parameter key id, key_type
  1468. function gpg_keyfile {
  1469. local GPG_KEY=$(gpg_key_legalize $1) TYPE="$2"
  1470. local KEYFILE="${KEYFILE//.asc/${GPG_KEY:+.$GPG_KEY}.asc}"
  1471. echo "${KEYFILE//.asc/${TYPE:+.$(tolower $TYPE)}.asc}"
  1472. }
  1473.  
  1474. # parameter key id
  1475. function gpg_import {
  1476. local i FILE FOUND=0 KEY_ID="$1" KEY_TYPE="$2" KEY_FP="" ERR=0
  1477. # create a list of legacy key file names and current naming scheme
  1478. # we always import pub and sec if they are avail in conf folder
  1479. local KEYFILES=( "$CONFDIR/gpgkey" $(gpg_keyfile "$KEY_ID") \
  1480. $(gpg_keyfile "$KEY_ID" PUB) $(gpg_keyfile "$KEY_ID" SEC))
  1481.  
  1482. # Try autoimport from existing old gpgkey files
  1483. # and new gpgkey.XXX.asc files (since v1.4.2)
  1484. # and even newer gpgkey.XXX.[pub|sec].asc
  1485. for (( i = 0 ; i < ${#KEYFILES[@]} ; i++ )); do
  1486. FILE=${KEYFILES[$i]}
  1487. if [ -f "$FILE" ]; then
  1488. FOUND=1
  1489.  
  1490. CMD_MSG="Import keyfile '$FILE' to keyring"
  1491. run_cmd gpg $GPG_OPTS --batch --import $(qw "$FILE")
  1492. if [ "$?" != "0" ]; then
  1493. warning "Import failed.${CMD_OUT:+\n$CMD_OUT}"
  1494. ERR=1
  1495. # continue with next
  1496. continue
  1497. fi
  1498. fi
  1499. done
  1500.  
  1501. if [ "$FOUND" -eq 0 ]; then
  1502. warning "No keyfile for '$KEY_ID' found in profile\n'$CONFDIR'."
  1503. fi
  1504.  
  1505. # try to set trust automagically
  1506. CMD_MSG="Autoset trust of key '$KEY_ID' to ultimate"
  1507. run_cmd echo $(gpg_fingerprint "$KEY_ID"):6: \| gpg $GPG_OPTS --import-ownertrust --batch --logger-fd 1
  1508. if [ "$?" = "0" ] && [ -z "$PREVIEW" ]; then
  1509. # success on all levels, we're done
  1510. return $ERR
  1511. fi
  1512.  
  1513. # failover: user has to set trust manually
  1514. echo -e "For $ME_NAME to work you have to set the trust level
  1515. with the command \"trust\" to \"ultimate\" (5) now.
  1516. Exit the edit mode of gpg with \"quit\"."
  1517. CMD_MSG="Running gpg to manually edit key '$KEY_ID'"
  1518. run_cmd sleep 5\; gpg $GPG_OPTS --edit-key $(qw "$KEY_ID")
  1519.  
  1520. return $ERR
  1521. }
  1522.  
  1523. # see 'How to specify a user ID' on gpg manpage
  1524. function gpg_fingerprint {
  1525. local PRINT=$(gpg $GPG_OPTS --fingerprint "$1" 2>&1|awk -F= 'NR==2{gsub(/ /,"",$2);$2=toupper($2); if ( $2 ~ /^[A-F0-9]+$/ && length($2) == 40 ) print $2; else exit 1}') \
  1526. && [ -n "$PRINT" ] && echo $PRINT && return 0
  1527. return 1
  1528. }
  1529.  
  1530. function gpg_export_if_needed {
  1531. local SUCCESS FILE KEY_TYPE
  1532. local TMPFILE="$TEMP_DIR/${ME_NAME}.$$.$(date_fix %s).gpgexp"
  1533. for KEY_ID in "$@"; do
  1534. # check if already exported, do it if not
  1535. for KEY_TYPE in PUB SEC; do
  1536. FILE="$(gpg_keyfile "$KEY_ID" $KEY_TYPE)"
  1537. if [ ! -f "$FILE" ] && eval gpg_$(tolower $KEY_TYPE)_avail \"$KEY_ID\"; then
  1538. # exporting
  1539. CMD_MSG="Backup $KEY_TYPE key '$KEY_ID' to profile."
  1540. # gpg2.1 insists on passphrase here, gpg2.0- happily exports w/o it
  1541. # we pipe an empty string when GPG_PW is not set to avoid gpg silently waiting for input
  1542. run_cmd $(gpg_pass_pipein GPG_PW_SIGN GPG_PW) gpg $GPG_OPTS $GPG_USEAGENT $(gpg_param_passwd GPG_PW_SIGN GPG_PW) --armor --export"$(test "SEC" = "$KEY_TYPE" && echo -secret-keys)" $(qw "$KEY_ID") '>>' $(qw "$TMPFILE")
  1543. CMD_ERR=$?
  1544.  
  1545. if [ "$CMD_ERR" = "0" ]; then
  1546. CMD_MSG="Write file '"$(basename "$FILE")"'"
  1547. run_cmd mv $(qw "$TMPFILE") $(qw "$FILE")
  1548. fi
  1549.  
  1550. if [ "$CMD_ERR" != "0" ]; then
  1551. warning "Backup failed.${CMD_OUT:+\n$CMD_OUT}"
  1552. else
  1553. SUCCESS=1
  1554. fi
  1555.  
  1556. # cleanup
  1557. rm $(qw "$TMPFILE") 1>/dev/null 2>&1
  1558. fi
  1559. done
  1560. done
  1561.  
  1562. [ -n "$SUCCESS" ] && inform "$ME_NAME exported new keys to your profile.
  1563. You should backup your changed profile folder now and store it in a safe place."
  1564. }
  1565.  
  1566. # replace all non-alnum chars with underscore (for file operations)
  1567. function gpg_key_legalize {
  1568. echo $* | awk '{gsub(/[^a-zA-Z0-9]/,"_",$0); print}'
  1569. }
  1570.  
  1571. function gpg_key_cache {
  1572. local RES
  1573. local MODE=$1
  1574. shift
  1575. local PREFIX="GPG_KEY"
  1576. local SUFFIX=$(gpg_key_legalize "$@")
  1577. local KEYID="$*"
  1578. local CACHE="${PREFIX}_${MODE}_${SUFFIX}"
  1579. if [ "$MODE" = "RESET" ]; then
  1580. eval unset ${PREFIX}_PUB_$SUFFIX ${PREFIX}_SEC_$SUFFIX
  1581. return 255
  1582. elif ! var_isset "$CACHE"; then
  1583. if [ "$MODE" = "PUB" ]; then
  1584. RES=$(gpg $GPG_OPTS --list-key "$KEYID" > /dev/null 2>&1; echo -n $?)
  1585. elif [ "$MODE" = "SEC" ]; then
  1586. RES=$(gpg $GPG_OPTS --list-secret-key "$KEYID" > /dev/null 2>&1; echo -n $?)
  1587. else
  1588. return 255
  1589. fi
  1590. eval $CACHE=$RES
  1591. fi
  1592. eval return \$$CACHE
  1593. }
  1594.  
  1595. function gpg_pub_avail {
  1596. gpg_key_cache PUB "$@"
  1597. }
  1598.  
  1599. function gpg_sec_avail {
  1600. gpg_key_cache SEC "$@"
  1601. }
  1602.  
  1603. function gpg_key_format {
  1604. echo $1 | grep -q '^[0-9a-fA-F]\{8\}$'
  1605. }
  1606.  
  1607. # splits a comma separated line into lines, respects escaped commas
  1608. function gpg_split_keyset {
  1609. local LIST
  1610. LIST=$(echo "$@" | awk '{ gsub(/,/,"\n",$0); gsub(/\\\n/,",",$0); print $0 }')
  1611. echo -e "$LIST"
  1612. }
  1613.  
  1614. function gpg_prefix_keyset {
  1615. local PREFIX="$1" OUT=""
  1616. shift
  1617. for KEY_ID in "$@"; do
  1618. OUT="${OUT} $PREFIX $(qw ${KEY_ID})"
  1619. done
  1620. echo $OUT
  1621. }
  1622.  
  1623. # grep a variable from conf text file (currently not used)
  1624. function gpg_passwd {
  1625. [ -r "$CONF" ] && \
  1626. awk '/^[ \t]*GPG_PW[ \t=]/{\
  1627. sub(/^[ \t]*GPG_PW[ \t]*=*/,"",$0);\
  1628. gsub(/^[ \t]*[\047"]|[\047"][ \t]*$/,"",$0);\
  1629. print $0; exit}' "$CONF"
  1630. }
  1631.  
  1632. # return success if at least one secret key is available
  1633. function gpg_key_decryptable {
  1634. local KEY_ID
  1635. for KEY_ID in "${GPG_KEYS_ENC_ARRAY[@]}"; do
  1636. gpg_sec_avail "$KEY_ID" && return 0
  1637. done
  1638. return 1
  1639. }
  1640.  
  1641. function gpg_symmetric {
  1642. [ -z "${GPG_KEY}${GPG_KEYS_ENC_ARRAY}" ]
  1643. }
  1644.  
  1645. # checks for max two params if they are set, typically GPG_PW & GPG_PW_SIGN
  1646. function gpg_param_passwd {
  1647. var_isset GPG_USEAGENT && exit 1
  1648.  
  1649. if ( [ -n "$1" ] && var_isset "$1" ) || ( [ -n "$2" ] && var_isset "$2" ); then
  1650. echo "--passphrase-fd 0 --batch"
  1651. fi
  1652. }
  1653.  
  1654. # select the earlist defined and create an "echo <value> |" string
  1655. function gpg_pass_pipein {
  1656. var_isset GPG_USEAGENT && exit 1
  1657.  
  1658. for var in "$@"
  1659. do
  1660. if var_isset "$var"; then
  1661. echo "echo $(qw $(eval echo \$$var)) |"
  1662. return 0
  1663. fi
  1664. done
  1665.  
  1666. return 1
  1667. }
  1668.  
  1669. # checks if gpg-agent is available, returns error code
  1670. # 0 on success
  1671. # 1 if GPG_AGENT_INFO is not set (unused, should probably be merged w/ 3)
  1672. # 2 if GPG_AGENT_INFO is stale
  1673. # 3 cannot connect to gpg-agent
  1674. function gpg_agent_avail {
  1675. # GPG_AGENT_INFO is deprecated in gpg2.1,
  1676. # first try to connect to a possibly running agent here
  1677. local ERR=3
  1678. gpg-agent > /dev/null 2>&1 && return 0
  1679.  
  1680. # detect stale pid in legacy GPG_AGENT_INFO env var
  1681. if var_isset GPG_AGENT_INFO; then
  1682. # check if a pid matching process is running at all
  1683. local GPG_AGENT_PID=$(echo $GPG_AGENT_INFO|awk -F: '{print $2}')
  1684. if isnumber "$GPG_AGENT_PID"; then
  1685. ps -p "$GPG_AGENT_PID" > /dev/null 2>&1 || ERR=2
  1686. fi
  1687. fi
  1688.  
  1689. return $ERR
  1690. }
  1691.  
  1692. function gpg_custom_binary {
  1693. var_isset GPG && [ "$GPG" != "$DEFAULT_GPG" ] &&\
  1694. echo "--gpg-binary $(qw "$GPG")"
  1695. }
  1696.  
  1697. function gpg_binary {
  1698. local BIN
  1699. var_isset GPG && BIN="$GPG" || BIN="$DEFAULT_GPG"
  1700. echo "$BIN"
  1701. }
  1702.  
  1703. function gpg_avail {
  1704. lookup "$(gpg_binary)"
  1705. }
  1706.  
  1707. # enforce the use of our selected gpg binary
  1708. function gpg {
  1709. command "$(gpg_binary)" "$@"
  1710. }
  1711. export -f gpg
  1712.  
  1713. # start of script #######################################################################
  1714.  
  1715. # confidentiality first, all we create is only readable by us
  1716. umask 077
  1717.  
  1718. # check if ftplicity is there & executable
  1719. [ -n "$ME_LONG" ] && [ -x "$ME_LONG" ] || error "$ME missing. Executable & available in path? ($ME_LONG)"
  1720.  
  1721. if [ ${#@} -eq 1 ]; then
  1722. cmd="${1}"
  1723. else
  1724. FTPLCFG="${1}" ; cmd="${2}"
  1725. fi
  1726.  
  1727. # deal with command before profile validation calls
  1728. # show requested version
  1729. # OR requested usage info
  1730. # OR create a profile
  1731. # OR fall through
  1732. ##if [ ${#@} -le 2 ]; then
  1733. case "$cmd" in
  1734. changelog)
  1735. changelog
  1736. exit 0
  1737. ;;
  1738. create)
  1739. set_config
  1740. if [ -d "$CONFDIR" ]; then
  1741. error "The profile '$FTPLCFG' already exists in
  1742. '$CONFDIR'.
  1743.  
  1744. Hint:
  1745. If you _really_ want to create a new profile by this name you will
  1746. have to manually delete the existing profile folder first."
  1747. exit 1
  1748. else
  1749. create_config
  1750. exit 0
  1751. fi
  1752. ;;
  1753. txt2man)
  1754. set_config
  1755. usage_txt2man
  1756. exit 0
  1757. ;;
  1758. usage|-help|--help|-h|-H)
  1759. set_config
  1760. usage_info
  1761. exit 0
  1762. ;;
  1763. version|-version|--version|-v|-V)
  1764. # profile can override GPG/PYTHON, so import it if it was given
  1765. var_isset FTPLCFG && {
  1766. set_config
  1767. [ -r "$CONF" ] && . "$CONF" || warning "Cannot import config '$CONF'."
  1768. }
  1769. version_info_using
  1770. exit 0
  1771. ;;
  1772. # fallthrough.. we got a command that needs an existing profile
  1773. *)
  1774. # if we reach here, user either forgot profile or chose wrong profileless command
  1775. if [ ${#@} -le 1 ]; then
  1776. error "\
  1777. Missing or wrong parameters.
  1778. Only the commands
  1779. changelog, create, usage, txt2man, version
  1780. can be called without selecting an existing profile first.
  1781. Your command was '$cmd'.
  1782.  
  1783. Hint: Run '$ME usage' to get help."
  1784. fi
  1785. esac
  1786.  
  1787.  
  1788. # Hello world
  1789. echo "Start $ME v$ME_VERSION, time is $(date_fix '%F %T')."
  1790.  
  1791. # check system environment
  1792.  
  1793. # is duplicity avail
  1794. lookup duplicity || error_path "duplicity missing. installed und available in path?"
  1795. # init, exec duplicity version check info
  1796. duplicity_python_binary_parse
  1797. duplicity_version_get
  1798.  
  1799. # check for certain important helper programs
  1800. for f in awk grep "$(python_binary)"; do
  1801. lookup "$f" || \
  1802. error_path "$f missing. installed und available in path?"
  1803. done
  1804.  
  1805. ### read configuration
  1806. set_config
  1807. # check validity
  1808. if [ ! -d "$CONFDIR" ]; then
  1809. error "Selected profile '$FTPLCFG' does not resolve to a profile folder in
  1810. '$CONFDIR'.
  1811.  
  1812. Hints:
  1813. Select one of the available profiles: $(for d in "$(dirname "$CONFDIR")"/*/; do [ -e "$d" ] || [ -L "$d" ] || continue; printf "$sep'$(basename "$d")'"; sep=",";done)
  1814. Use '$ME <name> create' to create a new profile.
  1815. Use '$ME usage' to get usage help."
  1816. elif [ ! -x "$CONFDIR" ]; then
  1817. error "\
  1818. Profile folder in '$CONFDIR' cannot be accessed.
  1819.  
  1820. Hint:
  1821. Check the filesystem permissions and set directory accessible e.g. 'chmod 700'."
  1822. elif [ ! -f "$CONF" ] ; then
  1823. error "'$CONF' not found."
  1824. elif [ ! -r "$CONF" ] ; then
  1825. error "'$CONF' not readable."
  1826. else
  1827. . "$CONF"
  1828. #KEYFILE="${KEYFILE//.asc/${GPG_KEY:+.$GPG_KEY}.asc}"
  1829. TEMP_DIR=${TEMP_DIR:-'/tmp'}
  1830. # backward compatibility: old TARGET_PW overrides silently new TARGET_PASS if set
  1831. if var_isset 'TARGET_PW'; then
  1832. TARGET_PASS="${TARGET_PW}"
  1833. fi
  1834. fi
  1835. echo "Using profile '$CONFDIR'."
  1836.  
  1837. # secure config dir, if needed w/ warning
  1838. secureconf
  1839.  
  1840. # split TARGET in handy variables
  1841. TARGET_SPLIT_URL=$(echo "$TARGET" | awk '{ \
  1842. target=$0; match(target,/^([^\/:]+):\/\//); \
  1843. prot=substr(target,RSTART,RLENGTH);\
  1844. rest=substr(target,RSTART+RLENGTH); \
  1845. if (credsavail=match(rest,/^[^@]*@/)){\
  1846. creds=substr(rest,RSTART,RLENGTH-1);\
  1847. credcount=split(creds,cred,":");\
  1848. rest=substr(rest,RLENGTH+1);\
  1849. # split creds with regexp\
  1850. match(creds,/^([^:]+)/);\
  1851. user=substr(creds,RSTART,RLENGTH);\
  1852. pass=substr(creds,RSTART+1+RLENGTH);\
  1853. };\
  1854. # filter quotes or escape them\
  1855. gsub(/[\047\042]/,"",prot);\
  1856. gsub(/[\047\042]/,"",rest);\
  1857. gsub(/[\047]/,"\047\\\047\047",creds);\
  1858. print "TARGET_URL_PROT=\047"prot"\047\n"\
  1859. "TARGET_URL_HOSTPATH=\047"rest"\047\n"\
  1860. "TARGET_URL_CREDS=\047"creds"\047\n";\
  1861. if(user){\
  1862. gsub(/[\047]/,"\047\\\047\047",user);\
  1863. print "TARGET_URL_USER=\047"user"\047\n"}\
  1864. if(pass){\
  1865. gsub(/[\047]/,"\047\\\047\047",pass);\
  1866. print "TARGET_URL_PASS=$(url_decode \047"pass"\047)\n"}\
  1867. }')
  1868. eval "${TARGET_SPLIT_URL}"
  1869.  
  1870. # fetch commmand from parameters ########################################################
  1871. # Hint: cmds is also used to check if authentification info sufficient in the next step
  1872. cmds="$2"; shift 2
  1873.  
  1874. # translate backup to batch command
  1875. cmds=${cmds//backup/pre_bkp_post}
  1876.  
  1877. # complain if command(s) missing
  1878. [ -z $cmds ] && error " No command given.
  1879.  
  1880. Hint:
  1881. Use '$ME usage' to get usage help."
  1882.  
  1883. # process params
  1884. for param in "$@"; do
  1885. #echo !$param!
  1886. case "$param" in
  1887. # enable ftplicity preview mode
  1888. '--preview')
  1889. PREVIEW=1
  1890.  ;;
  1891. # interpret duplicity disable encr switch
  1892. '--disable-encryption')
  1893. GPG_KEY='disabled'
  1894.  ;;
  1895. *)
  1896. if [ `echo "$param" | grep -e "^-"` ] || \
  1897. [ `echo "$last_param" | grep -e "^-"` ] ; then
  1898. # forward parameter[/option pairs] to duplicity
  1899. dupl_opts["${#dupl_opts[@]}"]=${param}
  1900. else
  1901. # anything else must be a parameter (eg. for fetch, ...)
  1902. ftpl_pars["${#ftpl_pars[@]}"]=${param}
  1903. fi
  1904. last_param=${param}
  1905.  ;;
  1906. esac
  1907. done
  1908.  
  1909. # plausibility check config - VARS & KEY ################################################
  1910. # check if src, trg, trg pw
  1911. # auth info sufficient
  1912. # gpg key, gpg pwd (might be empty) set in config
  1913. # OR key in local gpg db
  1914. # OR key can be imported from keyfile
  1915. # OR fail
  1916. if [ -z "$SOURCE" ] || [ "$SOURCE" == "${DEFAULT_SOURCE}" ]; then
  1917. error " Source Path (setting SOURCE) not set or still default value in conf file
  1918. '$CONF'."
  1919.  
  1920. elif [ -z "$TARGET" ] || [ "$TARGET" == "${DEFAULT_TARGET}" ]; then
  1921. error " Backup Target (setting TARGET) not set or still default value in conf file
  1922. '$CONF'."
  1923.  
  1924. elif var_isset 'TARGET_USER' && var_isset 'TARGET_URL_USER' && \
  1925. [ "${TARGET_USER}" != "${TARGET_URL_USER}" ]; then
  1926. error " TARGET_USER ('${TARGET_USER}') _and_ user in TARGET url ('${TARGET_URL_USER}')
  1927. are configured with different values. There can be only one.
  1928.  
  1929. Hint: Remove conflicting setting."
  1930.  
  1931. elif var_isset 'TARGET_PASS' && var_isset 'TARGET_URL_PASS' && \
  1932. [ "${TARGET_PASS}" != "${TARGET_URL_PASS}" ]; then
  1933. error " TARGET_PASS ('${TARGET_PASS}') _and_ password in TARGET url ('${TARGET_URL_PASS}')
  1934. are configured with different values. There can be only one.
  1935.  
  1936. Hint: Remove conflicting setting."
  1937. fi
  1938.  
  1939. # GPG config plausibility check1 (disabled check) #############################
  1940. if gpg_disabled; then
  1941.  : # encryption disabled, all is well
  1942. elif [ -z "${GPG_KEY}${GPG_KEYS_ENC}${GPG_KEY_SIGN}" ] && ! var_isset 'GPG_PW'; then
  1943. warning "GPG_KEY, GPG_KEYS_ENC, GPG_KEY_SIGN and GPG_PW are empty/not set in conf file
  1944. '$CONF'.
  1945. Will disable encryption for duplicity now.
  1946.  
  1947. Hint:
  1948. If you really want to use _no_ encryption you can disable this warning by
  1949. setting GPG_KEY='disabled' in conf file."
  1950. GPG_KEY='disabled'
  1951. fi
  1952.  
  1953. # GPG availability check (now we know if gpg is really needed)#################
  1954. if ! gpg_disabled; then
  1955. gpg_avail || error_path "gpg '$(gpg_binary)' missing. installed und available in path?"
  1956. fi
  1957.  
  1958. # Output versions info ########################################################
  1959. using_info
  1960.  
  1961. # GPG create key settings, config check2 (needs gpg) ##########################
  1962. if gpg_disabled; then
  1963.  : # the following tests are not necessary
  1964. else
  1965.  
  1966. # we test this early as any invocation gpg2.1+ starts gpg-agent automatically
  1967. GPG_AGENT_ERR=$(gpg_agent_avail ; echo $?)
  1968.  
  1969. # enc key still default?
  1970. if [ "$GPG_KEY" == "${DEFAULT_GPG_KEY}" ]; then
  1971. error_gpg "Encryption Key GPG_KEY still default in conf file
  1972. '$CONF'."
  1973. fi
  1974.  
  1975. # create array of gpg encr keys, for further processing
  1976. OIFS="$IFS" IFS=$'\n'
  1977. GPG_KEYS_ENC_ARRAY=( $( gpg_split_keyset ${GPG_KEY},${GPG_KEYS_ENC} ) )
  1978. IFS="$OIFS"
  1979.  
  1980. # pw set?
  1981. # symmetric needs one, always
  1982. if gpg_symmetric && ( [ -z "$GPG_PW" ] || [ "$GPG_PW" == "${DEFAULT_GPG_PW}" ] ) \
  1983.  ; then
  1984. error_gpg "Encryption passphrase GPG_PW (needed for symmetric encryption)
  1985. is empty/not set or still default value in conf file
  1986. '$CONF'."
  1987. fi
  1988. # this is a technicality, we can only pump one pass via pipe into gpg
  1989. # but symmetric already always needs one for encryption
  1990. if gpg_symmetric && var_isset GPG_PW && var_isset GPG_PW_SIGN &&\
  1991. [ -n "$GPG_PW_SIGN" ] && [ "$GPG_PW" != "$GPG_PW_SIGN" ]; then
  1992. error_gpg "GPG_PW _and_ GPG_PW_SIGN are defined but not identical in config
  1993. '$CONF'.
  1994. This is unfortunately impossible. For details see duplicity manpage,
  1995. section 'A Note On Symmetric Encryption And Signing'.
  1996.  
  1997. Tip: Separate signing keys may have empty passwords e.g. GPG_PW_SIGN=''.
  1998. Tip2: Use gpg-agent."
  1999. fi
  2000.  
  2001. # check gpg encr public keys availability
  2002. for (( i = 0 ; i < ${#GPG_KEYS_ENC_ARRAY[@]} ; i++ )); do
  2003. KEY_ID="${GPG_KEYS_ENC_ARRAY[$i]}"
  2004. # test availability, try to import, retest
  2005. if ! gpg_pub_avail "${KEY_ID}"; then
  2006. echo "Encryption public key '${KEY_ID}' not found."
  2007. gpg_import "${KEY_ID}" PUB
  2008. gpg_key_cache RESET "${KEY_ID}"
  2009. gpg_pub_avail "${KEY_ID}" || error_gpg_key "${KEY_ID}" "Public"
  2010. fi
  2011. done
  2012.  
  2013. # gpg secret sign key availability
  2014. # if none set, autoset first encryption key as sign key
  2015. if ! gpg_signing; then
  2016. echo "Signing disabled per configuration."
  2017. # try first key, if one set
  2018. elif ! var_isset 'GPG_KEY_SIGN'; then
  2019. KEY_ID="${GPG_KEYS_ENC_ARRAY[0]}"
  2020. if [ -z "${KEY_ID}" ]; then
  2021. echo "Signing disabled. No GPG_KEY entries in config."
  2022. GPG_KEY_SIGN='disabled'
  2023. else
  2024. # use avail OR try import OR fail
  2025. if gpg_sec_avail "${KEY_ID}"; then
  2026. GPG_KEY_SIGN="${KEY_ID}"
  2027. else
  2028. gpg_import "${KEY_ID}" SEC
  2029. gpg_key_cache RESET "${KEY_ID}"
  2030. if gpg_sec_avail "${KEY_ID}"; then
  2031. GPG_KEY_SIGN="${KEY_ID}"
  2032. fi
  2033. fi
  2034.  
  2035. # interpret sign key setting
  2036. if var_isset 'GPG_KEY_SIGN'; then
  2037. echo "Autoset found secret key of first GPG_KEY entry '${KEY_ID}' for signing."
  2038. else
  2039. echo "Signing disabled. First GPG_KEY entry's '${KEY_ID}' private key is missing."
  2040. GPG_KEY_SIGN='disabled'
  2041. fi
  2042. fi
  2043. else
  2044. KEY_ID="${GPG_KEY_SIGN}"
  2045. if ! gpg_sec_avail "${KEY_ID}"; then
  2046. inform "Secret signing key defined in setting GPG_KEY_SIGN='${KEY_ID}' not found.\nTry to import."
  2047. gpg_import "${KEY_ID}" SEC
  2048. gpg_key_cache RESET "${KEY_ID}"
  2049. gpg_sec_avail "${KEY_ID}" || error_gpg_key "${KEY_ID}" "Private"
  2050. fi
  2051. fi
  2052.  
  2053. # using GPG_AGENT_ERR set early above, try to autoenable gpg-agent or issue some warnings
  2054. # key enc can deal without, but might profit from gpg-agent
  2055. # if GPG_PW is not set alltogether
  2056. # if signing key is different from first (main) enc key (we can only pipe one pass into gpg)
  2057. if ! gpg_symmetric && \
  2058. ( ! var_isset GPG_PW || \
  2059. ( gpg_signing && ! var_isset GPG_PW_SIGN && [ "$GPG_KEY_SIGN" != "${GPG_KEYS_ENC_ARRAY[0]}" ] ) ); then
  2060.  
  2061. if [ "$GPG_AGENT_ERR" -eq 1 ]; then
  2062. warning "Cannot use gpg-agent. GPG_AGENT_INFO not set."
  2063. elif [ "$GPG_AGENT_ERR" -eq 2 ]; then
  2064. warning "Cannot use gpg-agent! GPG_AGENT_INFO contains stale pid."
  2065. elif [ "$GPG_AGENT_ERR" -eq 3 ]; then
  2066. warning "No running gpg-agent found although GPG_PW or GPG_PW_SIGN (enc != sign key) not set."
  2067. else
  2068. echo "Enable gpg-agent usage. Running gpg-agent instance found and GPG_PW or GPG_PW_SIGN (enc != sign key) not set."
  2069. GPG_USEAGENT="--use-agent"
  2070. fi
  2071. fi
  2072.  
  2073. # end GPG config plausibility check2
  2074. fi
  2075.  
  2076. # config plausibility check - SPACE ###########################################
  2077.  
  2078. # is tmp is a folder and writable
  2079. CMD_MSG="Checking TEMP_DIR '${TEMP_DIR}' is a folder and writable"
  2080. run_cmd test -d $(qw "$TEMP_DIR") '&&' test -w $(qw "$TEMP_DIR")
  2081. if [ "$?" != "0" ]; then
  2082. error "Temporary file space '$TEMP_DIR' is not a directory or writable."
  2083. fi
  2084.  
  2085.  
  2086. # get volsize, default duplicity volume size is 25MB since v0.5.07
  2087. VOLSIZE=${VOLSIZE:-25}
  2088. # double if asynch is on
  2089. echo $@ $DUPL_PARAMS | grep -q -e '--asynchronous-upload' && FACTOR=2 || FACTOR=1
  2090.  
  2091. # TODO: check for enough (async= upload space and WARN only
  2092. # use function tmp_space
  2093. #echo TODO: reimplent tmp space check
  2094.  
  2095.  
  2096. # test - GPG SANITY #####################################################################
  2097. # if encryption is disabled, skip this whole section
  2098. if gpg_disabled; then
  2099. echo -e "Test - En/Decryption skipped. (GPG disabled)"
  2100. elif [ "$GPG_TEST" = "disabled" ]; then
  2101. echo -e "Test - En/Decryption skipped. (Testing disabled)"
  2102. else
  2103.  
  2104. GPG_TEST="$TEMP_DIR/${ME_NAME}.$$.$(date_fix %s)"
  2105. function cleanup_gpgtest {
  2106. echo -en "Cleanup - Delete '${GPG_TEST}_*'"
  2107. rm "${GPG_TEST}"_* 2>/dev/null && echo "(OK)" || echo "(FAILED)"
  2108. }
  2109.  
  2110. # signing enabled?
  2111. if gpg_signing; then
  2112. CMD_PARAM_SIGN="--sign --default-key $(qw ${GPG_KEY_SIGN})"
  2113. CMD_MSG_SIGN="Sign with '${GPG_KEY_SIGN}'"
  2114. fi
  2115.  
  2116. # using keys
  2117. if [ ${#GPG_KEYS_ENC_ARRAY[@]} -gt 0 ]; then
  2118.  
  2119. for KEY_ID in "${GPG_KEYS_ENC_ARRAY[@]}"; do
  2120. CMD_PARAMS="$CMD_PARAMS -r $(qw ${KEY_ID})"
  2121. done
  2122. # check encrypting
  2123. CMD_MSG="Test - Encrypt to '$(join "','" "${GPG_KEYS_ENC_ARRAY[@]}")'${CMD_MSG_SIGN:+ & $CMD_MSG_SIGN}"
  2124. run_cmd $(gpg_pass_pipein GPG_PW_SIGN GPG_PW) gpg $CMD_PARAM_SIGN $(gpg_param_passwd GPG_PW_SIGN GPG_PW) $CMD_PARAMS $GPG_USEAGENT --status-fd 1 $GPG_OPTS -o $(qw "${GPG_TEST}_ENC") -e $(qw "$ME_LONG")
  2125. CMD_ERR=$?
  2126.  
  2127. if [ "$CMD_ERR" != "0" ]; then
  2128. KEY_NOTRUST=$(echo "$CMD_OUT"|awk '/^\[GNUPG:\] INV_RECP 10/ { print $4 }')
  2129. [ -n "$KEY_NOTRUST" ] && HINT="Key '${KEY_NOTRUST}' seems to be untrusted. If you really trust this key try to
  2130. 'gpg --edit-key "$KEY_NOTRUST"' and raise the trust level to ultimate. If you
  2131. can trust all of your keys set GPG_OPTS='--trust-model always' in conf file."
  2132. error_gpg_test "Encryption failed (Code $CMD_ERR).${CMD_OUT:+\n$CMD_OUT}" "$HINT"
  2133. fi
  2134.  
  2135. # check decrypting
  2136. CMD_MSG="Test - Decrypt"
  2137. gpg_key_decryptable || CMD_DISABLED="No matching secret key available."
  2138. run_cmd $(gpg_pass_pipein GPG_PW) gpg $(gpg_param_passwd GPG_PW) $GPG_OPTS -o $(qw "${GPG_TEST}_DEC") $GPG_USEAGENT -d $(qw "${GPG_TEST}_ENC")
  2139. CMD_ERR=$?
  2140.  
  2141. if [ "$CMD_ERR" != "0" ]; then
  2142. error_gpg_test "Decryption failed.${CMD_OUT:+\n$CMD_OUT}"
  2143. fi
  2144.  
  2145. # symmetric only
  2146. else
  2147. # check encrypting
  2148. CMD_MSG="Test - Encryption with passphrase${CMD_MSG_SIGN:+ & $CMD_MSG_SIGN}"
  2149. run_cmd $(gpg_pass_pipein GPG_PW) gpg $GPG_OPTS $CMD_PARAM_SIGN --passphrase-fd 0 -o $(qw "${GPG_TEST}_ENC") --batch -c $(qw "$ME_LONG")
  2150. CMD_ERR=$?
  2151. if [ "$CMD_ERR" != "0" ]; then
  2152. error_gpg_test "Encryption failed.${CMD_OUT:+\n$CMD_OUT}"
  2153. fi
  2154.  
  2155. # check decrypting
  2156. CMD_MSG="Test - Decryption with passphrase"
  2157. run_cmd $(gpg_pass_pipein GPG_PW) gpg $GPG_OPTS --passphrase-fd 0 -o $(qw "${GPG_TEST}_DEC") --batch -d $(qw "${GPG_TEST}_ENC")
  2158. CMD_ERR=$?
  2159. if [ "$CMD_ERR" != "0" ]; then
  2160. error_gpg_test "Decryption failed.${CMD_OUT:+\n$CMD_OUT}"
  2161. fi
  2162. fi
  2163.  
  2164. # compare original w/ decryptginal
  2165. CMD_MSG="Test - Compare"
  2166. [ -r "${GPG_TEST}_DEC" ] || CMD_DISABLED="File not found. Nothing to compare."
  2167. run_cmd "test \"\$(cat '$ME_LONG')\" = \"\$(cat '${GPG_TEST}_DEC')\""
  2168. CMD_ERR=$?
  2169. if [ "$CMD_ERR" = "0" ]; then
  2170. cleanup_gpgtest
  2171. else
  2172. error_gpg_test "Comparision failed.${CMD_OUT:+\n$CMD_OUT}"
  2173. fi
  2174.  
  2175. fi # end disabled
  2176.  
  2177. ## an empty line
  2178. #echo
  2179.  
  2180. # Exclude file is needed, create it if necessary
  2181. [ -f "$EXCLUDE" ] || touch "$EXCLUDE"
  2182.  
  2183. # export only used keys, if bkp not already exists ######################################
  2184. gpg_export_if_needed "${GPG_KEYS_ENC_ARRAY[@]}" "$(gpg_signing && echo $GPG_KEY_SIGN)"
  2185.  
  2186.  
  2187. # command execution #####################################################################
  2188.  
  2189. # urldecode url vars into plain text
  2190. var_isset 'TARGET_URL_USER' && TARGET_URL_USER="$(url_decode "$TARGET_URL_USER")"
  2191. var_isset 'TARGET_URL_PASS' && TARGET_URL_PASS="$(url_decode "$TARGET_URL_PASS")"
  2192.  
  2193. # defined TARGET_USER&PASS vars replace their URL pendants
  2194. # (double defs already dealt with)
  2195. var_isset 'TARGET_USER' && TARGET_URL_USER="$TARGET_USER"
  2196. var_isset 'TARGET_PASS' && TARGET_URL_PASS="$TARGET_PASS"
  2197.  
  2198. TARGET_URL_PROT_lowercase="$(tolower "${TARGET_URL_PROT%%:*}")"
  2199.  
  2200. # issue some warnings
  2201. case "$TARGET_URL_PROT_lowercase" in
  2202. 'cf+http')
  2203. # info on missing AUTH_URL
  2204. if ! var_isset 'CLOUDFILES_AUTHURL'; then
  2205. inform "No CLOUDFILES_AUTHURL exported (in conf).
  2206. Will use default which is probably rackspace."
  2207. fi
  2208.  ;;
  2209. 'swift')
  2210. # info on possibly missing AUTH_URL
  2211. var_isset 'SWIFT_AUTHURL' ||\
  2212. warning "\
  2213. Swift will probably fail because the conf var SWIFT_AUTHURL was not exported!"
  2214.  ;;
  2215. 'rsync')
  2216. # everything in url (this backend does not support pass in env var)
  2217. # this is obsolete from version 0.6.10 (buggy), hopefully fixed in 0.6.11
  2218. # print warning older version is detected
  2219. duplicity_version_lt 610 &&
  2220. warning "\
  2221. Duplicity version '$DUPL_VERSION' does not support providing the password as
  2222. env var for rsync backend. For security reasons you should consider to
  2223. update to a version greater than '0.6.10' of duplicity."
  2224.  ;;
  2225. esac
  2226.  
  2227.  
  2228. # for all protocols we put username in url and pass into env var
  2229. # for sec�rity reasons, we url_encode username to protect special chars
  2230. # first sortout backends with special ways to handle password
  2231. case "$TARGET_URL_PROT_lowercase" in
  2232. 'imap'|'imaps')
  2233. var_isset 'TARGET_URL_PASS' && BACKEND_PARAMS="IMAP_PASSWORD=$(qw "${TARGET_URL_PASS}")"
  2234.  ;;
  2235. *)
  2236. # rest uses FTP_PASS var
  2237. var_isset 'TARGET_URL_PASS' && \
  2238. BACKEND_PARAMS="FTP_PASSWORD=$(qw "${TARGET_URL_PASS}")"
  2239.  ;;
  2240. esac
  2241. # insert url encoded username into target url if needed
  2242. if var_isset 'TARGET_URL_USER' && [ "$TARGET_URL_PROT_lowercase" != "file" ]; then
  2243. BACKEND_URL="${TARGET_URL_PROT}$(url_encode "${TARGET_URL_USER}")@${TARGET_URL_HOSTPATH}"
  2244. else
  2245. BACKEND_URL="$TARGET"
  2246. fi
  2247.  
  2248.  
  2249. # protect eval from special chars in url (e.g. open ')' in password,
  2250. # spaces in path, quotes) happens above in duplify() via quotewrap()
  2251. SOURCE="$SOURCE"
  2252. BACKEND_URL="$BACKEND_URL"
  2253. EXCLUDE="$EXCLUDE"
  2254. # since 0.7.03 --exclude-globbing-filelist is deprecated
  2255. EXCLUDE_PARAM="--exclude$(duplicity_version_lt 703 && echo -globbing)-filelist"
  2256.  
  2257. # replace magic separators to condition command equivalents (+=and,-=or)
  2258. cmds=$(awk -v cmds="$cmds" "BEGIN{ gsub(/\+/,\"_and_\",cmds); gsub(/\-/,\"_or_\",cmds); print cmds}")
  2259. # convert cmds to array, lowercase for safety
  2260. CMDS=( $(awk "BEGIN{ cmds=tolower(\"$cmds\"); gsub(/_/,\" \",cmds); print cmds }") )
  2261.  
  2262. unset FTPL_ERR
  2263.  
  2264. # run cmds
  2265. for cmd in ${CMDS[*]};
  2266. do
  2267.  
  2268. ## init
  2269. # raise index in cmd array for pre/post param
  2270. var_isset 'CMD_NO' && CMD_NO=$((++CMD_NO)) || CMD_NO=0
  2271.  
  2272. # deal with condition "commands"
  2273. unset SKIP_NOW
  2274. if var_isset 'CMD_SKIP' && [ $CMD_SKIP -gt 0 ]; then
  2275. echo -e "\n--- Skipping command $(toupper $cmd) ! ---"
  2276. CMD_SKIP=$(($CMD_SKIP - 1))
  2277. SKIP_NOW="yes"
  2278. elif [ "$cmd" == 'and' ] && [ "$CMD_ERR" -ne "0" ]; then
  2279. CMD_SKIP=1
  2280. SKIP_NOW="yes"
  2281. elif [ "$cmd" == 'or' ] && [ "$CMD_ERR" -eq "0" ]; then
  2282. CMD_SKIP=1
  2283. SKIP_NOW="yes"
  2284. elif [ "$cmd" == 'and' ] || [ "$cmd" == 'or' ]; then
  2285. unset 'CMD_SKIP';
  2286. SKIP_NOW="yes"
  2287. fi
  2288.  
  2289. # sum up how many commands we skip and actually skip
  2290. if [ -n "$SKIP_NOW" ]; then
  2291. CMD_SKIPPED=$((${CMD_SKIPPED-0} + 1))
  2292. continue
  2293. fi
  2294.  
  2295. unset CMD_VALUE CMD_NEXT CMD_PREV CND_NEXT CND_PREV
  2296.  
  2297. # get next cmd,cnd vars
  2298. nextno=$(( $CMD_NO + 1 ))
  2299. while ! var_isset 'CMD_NEXT'
  2300. do
  2301. if [ "$nextno" -lt "${#CMDS[@]}" ]; then
  2302. CMD_VALUE=${CMDS[$nextno]}
  2303. is_condition "$CMD_VALUE" && CND_NEXT="$CMD_VALUE" || CMD_NEXT="$CMD_VALUE"
  2304. else
  2305. CMD_NEXT='END'
  2306. fi
  2307. nextno=$(($nextno+1))
  2308. done
  2309.  
  2310. # get prev cnd, cnd are skipped pseudocmds
  2311. prevno=$(( $CMD_NO - 1 ))
  2312. [ "$prevno" -ge 0 ] && is_condition "${CMDS[$prevno]}" && CND_PREV=${CMDS[$prevno]}
  2313.  
  2314. # get prev cmd command minus skipped commands, only executed
  2315. prevno=$(( $CMD_NO - ${CMD_SKIPPED-0} - 1 )); unset CMD_SKIPPED
  2316. while ! var_isset 'CMD_PREV'
  2317. do
  2318. if [ "$prevno" -ge 0 ]; then
  2319. CMD_VALUE=${CMDS[$prevno]}
  2320. is_condition "$CMD_VALUE" || CMD_PREV="$CMD_VALUE"
  2321. else
  2322. CMD_PREV='START'
  2323. fi
  2324. prevno=$(($prevno-1))
  2325. done
  2326.  
  2327. # save start time
  2328. RUN_START=$(nsecs)
  2329.  
  2330. # export some useful env vars for external scripts/programs to use
  2331. export PROFILE CONFDIR SOURCE TARGET_URL_PROT TARGET_URL_HOSTPATH \
  2332. TARGET_URL_USER TARGET_URL_PASS \
  2333. GPG_KEYS_ENC=$(join "\n" "${GPG_KEYS_ENC_ARRAY[@]}") GPG_KEY_SIGN \
  2334. GPG_PW CMD_PREV CMD_NEXT CMD_ERR CND_PREV CND_NEXT\
  2335. RUN_START
  2336.  
  2337. # user info
  2338. echo; separator "Start running command $(toupper $cmd) at $(date_from_nsecs $RUN_START)"
  2339.  
  2340. case "$(tolower $cmd)" in
  2341. 'pre'|'post')
  2342. if [ "$cmd" == 'pre' ]; then
  2343. script=$PRE
  2344. else
  2345. script=$POST
  2346. fi
  2347. # script execution in a subshell, protect us from failures/var overwrites
  2348. ( run_script "$script" )
  2349.  ;;
  2350. 'bkp')
  2351. duplify -- "${dupl_opts[@]}" $EXCLUDE_PARAM "$EXCLUDE" \
  2352. "$SOURCE" "$BACKEND_URL"
  2353.  ;;
  2354. 'incr')
  2355. duplify incr -- "${dupl_opts[@]}" $EXCLUDE_PARAM "$EXCLUDE" \
  2356. "$SOURCE" "$BACKEND_URL"
  2357.  ;;
  2358. 'full')
  2359. duplify full -- "${dupl_opts[@]}" $EXCLUDE_PARAM "$EXCLUDE" \
  2360. "$SOURCE" "$BACKEND_URL"
  2361.  ;;
  2362. 'verify')
  2363. TIME="${ftpl_pars[0]:+"-t ${ftpl_pars[0]}"}"
  2364. duplify verify -- $TIME "${dupl_opts[@]}" $EXCLUDE_PARAM "$EXCLUDE" \
  2365. "$BACKEND_URL" "$SOURCE"
  2366.  ;;
  2367. 'verifypath')
  2368. TIME="${ftpl_pars[2]:+"-t ${ftpl_pars[2]}"}"
  2369. IN_PATH="${ftpl_pars[0]}"; OUT_PATH="${ftpl_pars[1]}";
  2370. ( [ -z "$IN_PATH" ] || [ -z "$OUT_PATH" ] ) && error " Missing parameter <rel_bkp_path> or <local_path> for verifyPath.
  2371.  
  2372. Hint:
  2373. Syntax is -> $ME <profile> verifyPath <rel_bkp_path> <local_path> [<age>]"
  2374.  
  2375. duplify verify -- $TIME "${dupl_opts[@]}" $EXCLUDE_PARAM "$EXCLUDE" \
  2376. --file-to-restore "$IN_PATH" "$BACKEND_URL" "$OUT_PATH"
  2377.  ;;
  2378. 'list')
  2379. # time param exists since 0.5.10+
  2380. TIME="${ftpl_pars[0]:+"-t ${ftpl_pars[0]}"}"
  2381. duplify list-current-files -- $TIME "${dupl_opts[@]}" "$BACKEND_URL"
  2382.  ;;
  2383. 'cleanup')
  2384. duplify cleanup -- "${dupl_opts[@]}" "$BACKEND_URL"
  2385.  ;;
  2386. 'purge')
  2387. MAX_AGE=${ftpl_pars[0]:-$MAX_AGE}
  2388. [ -z "$MAX_AGE" ] && error " Missing parameter <max_age>. Can be set in profile or as command line parameter."
  2389.  
  2390. duplify remove-older-than "${MAX_AGE}" \
  2391. -- "${dupl_opts[@]}" "$BACKEND_URL"
  2392.  ;;
  2393. 'purgefull')
  2394. MAX_FULL_BACKUPS=${ftpl_pars[0]:-$MAX_FULL_BACKUPS}
  2395. [ -z "$MAX_FULL_BACKUPS" ] && error " Missing parameter <max_full_backups>. Can be set in profile or as command line parameter."
  2396.  
  2397. duplify remove-all-but-n-full "${MAX_FULL_BACKUPS}" \
  2398. -- "${dupl_opts[@]}" "$BACKEND_URL"
  2399.  ;;
  2400. 'purgeincr')
  2401. MAX_FULLS_WITH_INCRS=${ftpl_pars[0]:-$MAX_FULLS_WITH_INCRS}
  2402. [ -z "$MAX_FULLS_WITH_INCRS" ] && error " Missing parameter <max_fulls_with_incrs>. Can be set in profile or as command line parameter."
  2403.  
  2404. duplify remove-all-inc-of-but-n-full "${MAX_FULLS_WITH_INCRS}" \
  2405. -- "${dupl_opts[@]}" "$BACKEND_URL"
  2406.  ;;
  2407. 'restore')
  2408. OUT_PATH="${ftpl_pars[0]}"; TIME="${ftpl_pars[1]:-now}";
  2409. [ -z "$OUT_PATH" ] && error " Missing parameter target_path for restore.
  2410.  
  2411. Hint:
  2412. Syntax is -> $ME <profile> restore <target_path> [<age>]"
  2413.  
  2414. duplify -- -t "$TIME" "${dupl_opts[@]}" "$BACKEND_URL" "$OUT_PATH"
  2415.  ;;
  2416. 'fetch')
  2417. IN_PATH="${ftpl_pars[0]}"; OUT_PATH="${ftpl_pars[1]}";
  2418. TIME="${ftpl_pars[2]:-now}";
  2419. ( [ -z "$IN_PATH" ] || [ -z "$OUT_PATH" ] ) && error " Missing parameter <src_path> or <target_path> for fetch.
  2420.  
  2421. Hint:
  2422. Syntax is -> $ME <profile> fetch <src_path> <target_path> [<age>]"
  2423.  
  2424. # duplicity 0.4.7 doesnt like cmd restore in combination with --file-to-restore
  2425. duplify -- --restore-time "$TIME" "${dupl_opts[@]}" \
  2426. --file-to-restore "$IN_PATH" "$BACKEND_URL" "$OUT_PATH"
  2427.  ;;
  2428. 'status')
  2429. duplify collection-status -- "${dupl_opts[@]}" "$BACKEND_URL"
  2430.  ;;
  2431. *)
  2432. error " Unknown command '$cmd'.
  2433.  
  2434. Hint:
  2435. Use '$ME usage' to get usage help."
  2436.  ;;
  2437. esac
  2438.  
  2439. CMD_ERR=$?
  2440. RUN_END=$(nsecs)
  2441. RUNTIME=$(( $RUN_END - $RUN_START ))
  2442.  
  2443. # print message on error; set error code
  2444. if [ "$CMD_ERR" -ne 0 ]; then
  2445. error_print "$(datefull_from_nsecs $RUN_END) Task '$(echo $cmd|awk '$0=toupper($0)')' failed with exit code '$CMD_ERR'."
  2446. FTPL_ERR=1
  2447. fi
  2448.  
  2449. separator "Finished state $(error_to_string $CMD_ERR) at $(date_from_nsecs $RUN_END) - \
  2450. Runtime $(printf "%02d:%02d:%02d.%03d" $((RUNTIME/1000000000/60/60)) $((RUNTIME/1000000000/60%60)) $((RUNTIME/1000000000%60)) $((RUNTIME/1000000%1000)) )"
  2451.  
  2452. done
  2453.  
  2454. exit ${FTPL_ERR}
  2455.