Duply-code

From duply
Revision as of 12:14, 17 December 2015 by Edso (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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 #$system:stat -c%y tmp/duply.sh| awk '{print $1}'#

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