[
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# snapraid-btrfs\n\n`snapraid-btrfs` is a script for using [SnapRAID](http://www.snapraid.it/) with\ndata drives which are formatted with btrfs. It allows operations such as\n`snapraid sync` or `snapraid scrub` which do not write to the data drives to be\ndone using read-only snapshots, and when running SnapRAID operations which do\nwrite to the data drives (i.e., `snapraid fix` and `snapraid touch`) it creates\nbefore and after snapshots. It aims to be a transparent wrapper around the\n`snapraid` command, allowing you to replace, e.g., `snapraid sync` with\n`snapraid-btrfs sync`, and works by creating a temporary SnapRAID configuration\nfile where the data paths are replaced with those of corresponding read-only\nsnapshots, then running `snapraid` using the temporary configuration file.\n\nOptions appearing before the command (e.g., `sync` or `scrub`) control the\nbehavior of `snapraid-btrfs`, while options appearing after the command are\npassed through to `snapraid`, with the exception of `-c`/`--conf`, which is\nreserved for use by `snapraid-btrfs` to point `snapraid` to its temporary\nconfiguration file, and which can instead be specified as a `snapraid-btrfs`\noption, before the command, so that it can be processed by `snapraid-btrfs`\nwhen creating the temporary SnapRAID config file. For example,\n`snapraid-btrfs -c /foo/snapraid.conf sync -v` would run\n`snapraid sync -c /tmp/example -v`, where `/tmp/example` was generated using\n`/foo/snapraid.conf` instead of `/etc/snapraid.conf`. `snapraid-btrfs` also\nimplements additional commands, such as `cleanup`, for managing its snapshots.\n\n## Setup instructions\n\nTo start using `snapraid-btrfs`, you need to set up\n[snapper](http://snapper.io/) configurations for each data drive that you want\n`snapraid-btrfs` to make snapshots of. At runtime, `snapraid-btrfs` will follow\nthe following procedure to find snapper configs:\n\n- If the `--snapper-configs` or `--snapper-configs-file` command-line options\n  are set, look at only the configs specified there, and no others.\n- Else, look at filenames in `/etc/snapper/configs` (or an alternate directory\n  specified by setting the `SNAPPER_CONFIG_DIR` environment variable) to get\n  the names of snapper configs. This directory should be readable by the user\n  running `snapraid-btrfs`, but the files inside it need not be.\n- For each config found, attempt to read the `SUBVOLUME` variable using\n  `snapper get-config`. If this command fails (generally because the user is\n  not included in `ALLOW_USERS` or `ALLOW_GROUPS`), skip the config.\n- If successful in reading `SUBVOLUME`, attempt to find a matching data drive\n  in the SnapRAID configuration file.\n- If configs are specified with `--snapper-configs` or `--snapper-configs-file`\n  then `snapraid-btrfs` expects them all to match data drives in the SnapRAID\n  configuration file, and will display an error message and exit if\n  `snapper get-config` fails or `SUBVOLUME` does not match.\n\n`snapraid-btrfs` will ignore any data drives which it does not find\ncorresponding snapper configs for (in other words, the live filesystem will be\nused for all operations and no snapshots will be created. Just like SnapRAID,\n`snapraid-btrfs` will use `/etc/snapraid.conf` by default, but another\nconfiguration file can be specified using the `-c`/`--conf` option, or by\nsetting the `SNAPRAID_CONFIG_FILE` environment variable.\n\nAll files on the data drives which are not excluded by the SnapRAID\nconfiguration file must be in the same subvolume. **If any of the SnapRAID\n\"content\" files are stored on data drives, create a dedicated subvolume for\nthem so that they are not snapshotted.** It is also recommended that you add\nthe line `exclude /.snapshots/` to your SnapRAID configuration file, so that if\nyou ever run `snapraid sync` instead of `snapraid-btrfs sync`, SnapRAID will\nnot try to sync both the live filesystem and the read-only snapshots, causing\nit to display a warning message about the snapshots being in a different\nfilesystem (since SnapRAID sees subvolumes as different filesystems, it will\nnot try to sync the snapshots in any case, so actual behavior is unaffected).\n\nSee the FAQ below for more details. To verify that snapper has been set up\ncorrectly, you can use the `snapraid-btrfs ls` command, which will run\n`snapper ls` for all of the snapper configurations that it recognizes as\nmatching data drives in your SnapRAID configuration file. If `snapraid-btrfs`\ndoes not find all of the snapper configs you were expecting, try using the\n`--verbose` option. Once you are satisfied that `snapraid-btrfs` has found all\nof your configs, you are ready to run your first `snapraid-btrfs sync` which\nwill, by default, create new snapshots and use them for the sync. For more\ndetails on using `snapraid-btrfs`, see the output of `snapraid-btrfs --help`.\n\n## Dependencies\n\n- [SnapRAID](http://www.snapraid.it/)\n- [snapper](http://snapper.io/)\n- [bash](https://www.gnu.org/software/bash/) (version 4.1+)\n- awk, sed, grep, and coreutils (should all be installed by default in any\n  modern distro, and any POSIX-compliant versions should work, as nonportable\n  features are avoided)\n\nAll dependencies are checked on startup, and if any of them are not found,\n`snapraid-btrfs` will display an error message and exit. Note that by default,\n`snapraid-btrfs` will search for `snapraid` and `snapper` in the user's `PATH`,\nbut alternatively, the `--snapper-path` and/or `--snapraid-path` command line\noptions can be specified.\n\n`#!/bin/bash` is used as the shebang (as the `#!/usr/bin/env bash` trick has\ndisadvantages), so if a compatible version of bash cannot be found there, one\nof the following workarounds must be used:\n\n- Create a symlink. This is generally already done on distros that have done\n  the `/usr` merge and install bash in `/usr/bin` instead of `/bin`.\n- Run `snapraid-btrfs` using `/path/to/right/bash /path/to/snapraid-btrfs`,\n  possibly by creating a wrapper script or shell alias\n- Manually edit the first line of the script to point to the correct location\n\n## FAQ\n\n### Q: Why use snapraid-btrfs?\nA: A major disadvantage of SnapRAID is that the parity files are not updated in\nrealtime. This not only means that new files are not protected until after\nrunning `snapraid sync`, but also creates a form of \"write hole\" where if files\nare modified or deleted, some protection of other files which share the same\nparity block(s) is lost until another sync is completed, since if other files\nneed to be restored using the `snapraid fix` command, the deleted or modified\nfiles will not be available, just as if the disk had failed, or developed a bad\nsector. This problem can be mitigated by adding additional parities, since\nSnapRAID permits up to six, or worked around by temporarily moving files into a\ndirectory that is excluded in your SnapRAID config file, then completing a sync\nto remove them from the parity before deleting them. However, this problem is a\ntextbook use case for btrfs snapshots.\n\nBy using read-only snapshots when we do a `snapraid sync`, we ensure that if we\nmodify or delete files during or after the sync, we can always restore the\narray to the state it was in at the time the read-only snapshots were created,\nso long as the snapshots are not deleted until another sync is completed with\nnew snapshots. This use case for btrfs snapshots is similar to using\n`btrfs send/receive` to back up a live filesystem, where the use of read-only\nsnapshots guarantees the consistency of the result, while using `dd` would\nrequire that the entire filesystem be mounted read-only to prevent corruption\ncaused by writes to the live filesystem during the backup.\n\n### Q: Are all SnapRAID commands supported?\nA: Only the ones which either read from or write to the data drives, since for\nthe others (e.g. `snapraid smart`), there is no benefit to using btrfs\nsnapshots. Note that `snapraid-btrfs` does not interfere with the ability to\ninvoke SnapRAID directly, allowing you to use these commands, or any other\nSnapRAID command, with `snapraid-btrfs` temporarily disabled.\n\n### Q: Do I need to use btrfs for all of the data drives?\nA: No. Any drives that don't have a corresponding snapper configuration will be\nignored (meaning that the live filesystem will be used). This allows you to\nformat data drives with any filesystem supported by SnapRAID. However, the\nprotection offered by `snapraid-btrfs` will not be available for writes made to\nany data drives that it does not manage.\n\n### Q: What about the parity drives?\nA: Since the parity files are (or, at least, should be) only written to during\n`snapraid sync` operations, there is no need to snapshot them, as the parity\nfiles will always correspond with the read-only snapshots they were created\nfrom. If a sync is interrupted, different sets of snapshots will correspond\nwith different portions of the parity file(s), and both sets of snapshots\nshould be retained until a sync is completed, at which point all previous\nsnapshots can be safely cleaned up. A snapper userdata key is used to keep\ntrack of whether a `snapraid sync` run on a set of snapshots completes\nsuccessfully (i.e., returns exit status 0) to ensure that\n`snapraid-btrfs cleanup` can handle this situation properly.\n\nIt is recommended that you use ext4 for the parity drives, since the metadata\noverhead is extremely small with the right mkfs settings (minimum possible\nnumber of inodes, minimum journal size (or journaling disabled), and no space\nreserved for root - see `man mke2fs` for more details), and because for the\nparity drives, there is no real use for any of the features which btrfs\noffers over ext4.\n\n### Q: What about the SnapRAID \"content\" files?\nA: Just like the parity files, these do not need to be snapshotted. If they are\nstored on the data drives, they should be in a dedicated subvolume, separate\nfrom the one where the data is stored.\n\n### Q: What about the space consumed by the snapshots?\nA: Running out of parity space is not an issue (at least, no more of an issue\nthan it is without the use of snapshots), since only one snapshot at a time is\nused for a sync. You may temporarily run out of space on the data drives if you\nreplace existing files with new data, but you can always free up that space by\ndoing a new sync with new snapshots, and then deleting the old snapshots using\nthe `snapraid-btrfs cleanup` command.\n\nIn the worst case (which occurs when the array is almost full), as changes are\nmade to the array, the use of snapshots will double the time spent syncing the\nchanges into the parity, but the capacity of the array will not be affected.\nTo the extent you do not have extra space to spare, after deleting files, you\nwill have to sync them out of the parity before the space they occupy can be\nfreed using `snapraid-btrfs cleanup`, allowing you to add new files, following\nwhich a second sync operation would be required to add them to the parity.\n\nIf you have enough space to spare, you can add the new data before the initial\nsync instead of waiting until after the post-sync cleanup, in which case the\nspeed of syncing is no different than without `snapraid-btrfs`. And you can\nreduce the amount of free space required to avoid the worst-case behavior by\nsyncing more frequently, before the live filesystem diverges too much from the\nsnapshots, and always running `snapraid-btrfs cleanup` after each successful\nsync.\n\nThis is an unavoidable limitation of the protection provided by\n`snapraid-btrfs`, and the same price would be paid for any solution to the\nproblem `snapraid-btrfs` aims to solve - e.g. moving files to a directory which\nis excluded in the SnapRAID config file before deleting them. To preserve the\nability to restore the array to the state it was in at the time of the last\nsync even if files are modified or deleted, those files must be saved somewhere\nuntil the parity has been brought up to date.\n\n### Q: Does snapraid-btrfs need to be run as root?\nA: No, and it is recommended that you do not do so, just as you should not run\nSnapRAID as root.\n\n### Q: Is there a snapraid-btrfs configuration file?\nA: No. An explicit design goal of `snapraid-btrfs` is to not require a\nconfiguration file of its own. Nor does it require a file to store state\ninformation and keep track of its snapshots, because that information is stored\nas snapper userdata.\n\n### Q: How do I make sure my user (or group) has the necessary permissions?\nA: Assuming you already have a working SnapRAID configuration, you just need to\nconfigure snapper correctly. See \"How do I set up snapper for use with\n`snapraid-btrfs`?\" below.\n\n### Q: How do I configure snapper for use with snapraid-btrfs?\nA: Create a snapper configuration for each data drive you want to use\n`snapraid-btrfs` for, and make sure to set `SYNC_ACL=yes` in addition to\n`ALLOW_USERS` or `ALLOW_GROUPS` for the user(s) and/or group(s) which will run\nsnapraid-btrfs in your snapper configurations. You may wish to make a snapper\ntemplate with the options you want to use for your SnapRAID drive\nconfigurations and set these variables at that level. For further details, see\nthe snapper documentation.\n\n### Q: What about my snapraid.conf file? Do I need to do anything there?\nA: `snapraid-btrfs` is designed to work with your existing SnapRAID\nconfiguration without requiring further changes. However, you may wish to add\nthe line `exclude /.snapshots/` to your config file. If you ever plan to sync\nyour SnapRAID configuration without using `snapraid-btrfs` (or disable it for\nspecific drives using the command-line options), SnapRAID will see the\n`.snapshots` subvolume as a separate filesystem and warn you that it won't be\nincluded in the parity. Excluding it explicitly will prevent you from receiving\nthis warning message from SnapRAID.\n\nWhen using `snapraid-btrfs` to sync, the `.snapshots` subvolume will appear as\nan empty directory in the read-only snapshots, so excluding it in the SnapRAID\nconfig file is unnecessary, but harmless. (The `.snapshots` directory is\nexcluded relative to the root of the data drives, so if your data drive is\nmounted at `/foo/bar` then if using snapshot n it will exclude\n`/foo/bar/.snapshots/n/snapshot/.snapshots`, and if using the live filesystem\nit will exclude `/foo/bar/.snapshots`.)\n\nSimilarly, if you store any of your content files in subvolumes which have\nmountpoints underneath the data subvolume, you should `exclude` those paths to\navoid receiving warnings from SnapRAID. For instance, if data is stored in\n`/path/to/snapraid/1/data` and content in `/path/to/snapraid/1/content` then\nno `exclude` would be required, but if the content subvolume is mounted\nunderneath the data subvolume, e.g. at `/path/to/snapraid/1/data/content`, then\nan `exclude` statement would be needed to avoid a warning from SnapRAID. See\n\"What about the SnapRAID content files?\" below.\n\n### Q: Can I have multiple subvolumes on a single data drive?\nA: `snapraid-btrfs` only uses one subvolume per data drive, which should\ncontain all the data which is to be protected by SnapRAID, and should have a\nsnapper config with the `SUBVOLUME` variable matching the path in the SnapRAID\nconfig file. **Any files stored in other subvolumes on the data drives will NOT\nbe protected by the parity, even if those subvolumes are mounted below the path\nspecified in the SnapRAID config file.** This is because syncs will be done\nusing a read-only snapshot, where the subvolume mount point will appear to\nSnapRAID as an empty directory. Also, SnapRAID currently sees separate btrfs\nsubvolumes as separate filesystems, so this wouldn't work even without\nusing snapshots.\n\nIn any case, it's desirable to have all the SnapRAID data files in a single\nsubvolume, since this makes snapshotting atomic, ensuring that after a\nsuccessful sync, the parity corresponds to a single snapshot of each data\ndrive.\n\n### Q: What about the SnapRAID content files?\nThe SnapRAID \"content\" files should be stored in a separate subvolume to\nprevent them from being snapshotted. `snapraid-btrfs` will display an error\nmessage and refuse to run if this is not done.\n\n### Q: Can I also manage snapshots manually with snapper?\nA: Yes. `snapraid-btrfs` keeps track of its own snapshots using a snapper\nuserdata key, and will ignore any snapshots without that userdata key defined.\nIf you delete `snapraid-btrfs` snapshots using snapper, parity protection may\nbe lost, so it is recommended that you use the `snapraid-btrfs cleanup` command\ninstead, which will only delete snapshots when it is safe to do so (and will\nignore any snapshots without that userdata key specified). If you need to free\nup space by deleting old snapshots, it is recommended that you complete a new\nsync with a fresh set of snapshots (which will initially require no space since\nthey will be identical to the live filesystem), then run the\n`snapraid-btrfs cleanup` command to delete the old ones.\n\n### Q: Can I change the snapper userdata key that is used to track snapshots?\nA: Yes. If the `SNAPRAID_USERDATA_KEY` environment variable is set,\n`snapraid-btrfs` will use that as its userdata key. Otherwise, it will default\nto `snapraid-btrfs`. Beware that if you change this, snapshots created before\nthe change will no longer be identified as having been created by\n`snapraid-btrfs`.\n\n### Q: Can I restore a previous snapshot?\nA: Just like with \"vanilla\" SnapRAID, a fix can only restore the array to the\nstate that it was in at the time of the last sync. This is because the parity\nfiles can only correspond to one snapshot at a time, and is a fundamental\nlimitation of SnapRAID due to its file-based nature.\n\nThe purpose of `snapraid-btrfs` is simply to ensure that modifying the array\nafter a sync doesn't delete any of the data that would be required for the\nfix operation. If you want multiple snapshots protected by parity, you'll\nneed to use another solution such as mdadm or btrfs RAID that operates at\nthe filesystem or block device level.\n\nThe above only refers to what is possible with `snapraid fix` (whether or not\ninvoked via `snapraid-btrfs fix`). Of course, you can still revert individual\ndata disks, or the entire array, to a previous state, just as with any btrfs\nfilesystem. You just won't be able to make use of the parity to reconstruct\ndata in older snapshots if a disk fails.\n\n### Q: What is the 'dsync' command and what is it for?\nA: Short for `diff-sync`, this command creates a set of read-only snapshots,\nruns a `snapraid diff`, and then asks for confirmation before running a\n`snapraid sync` with the same snapshots. Since SnapRAID can only restore the\narray to the state it was in at the time of the last sync, syncing is a\ndestructive action, and the `dsync` command allows the user to make sure the\nnew snapshots are okay before continuing with the sync. Since the sync will\nonly be run after the user has approved the diff, the `--force-empty` option is\npassed through to `snapraid`. The behavior of this command is equivalent to\nrunning `snapraid-btrfs diff` followed by\n`snapraid-btrfs --interactive --use-snapshot-all=diff sync --force-empty`,\nexcept that `snapraid-btrfs dsync` will only run the sync if `snapraid diff`\nindicates that there have been changes since the last sync. Otherwise,\n`snapraid-btrfs dsync` will simply exit after the diff.\n\n### Q: What about pooling?\nA: If you run `snapraid-btrfs pool` the symlinks created in your pool directory\n(or in the directory specified with the `--pool-dir` option) will be to the\nread-only snapshots instead of the live filesystem. This may or may not be what\nyou want; if you want the symlinks to point to the live filesystem, you can\nstill use the `snapraid pool` command as normal, or you can even have both in\ndifferent directories by making use of the `--pool-dir` option. If you do use\n`snapraid-btrfs pool` you should re-run it after each sync. This will not only\nkeep the symlinks up to date with any changes, but also ensures that a\n`snapraid-btrfs cleanup` operation doesn't result in broken symlinks that point\nto deleted snapshots.\n\n### Q: How do I stop using snapraid-btrfs?\nA: Just complete a full sync, invoking SnapRAID directly and not via\n`snapraid-btrfs`. Then your parity files will be up to date with the live\nfilesystem, and you can safely delete all snapshots using\n`snapraid-btrfs cleanup-all` and have a regular SnapRAID configuration.\n\n## Known issues\n* SnapRAID won't be able to properly detect the UUID when using a snapshot, so\nit won't be able to use inodes to detect move operations. As a workaround, you\ncan temporarily disable `snapraid-btrfs`, either globally by doing a regular\n`snapraid sync`, or for specific drives by doing a `snapraid-btrfs sync` using\nthe `-U` option to select snapshot 0 (i.e., the live filesystem, in snapper\nterminology) for the drives in question, moving the files, doing another sync\nwith `snapraid-btrfs` disabled, and then reenabling `snapraid-btrfs` by doing a\nnormal `snapraid-btrfs sync`.\n\n## License\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <http://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "snapraid-btrfs",
    "content": "#!/bin/bash -\n\n# Copyright (C) 2017-2023 Alex deBeus\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nreadonly COPYRIGHT_YEARS='2017-2023'\nreadonly DEFAULT_CONFIG_FILE=/etc/snapraid.conf\nreadonly DEFAULT_SNAPPER_CONFIG_DIR=/etc/snapper/configs\nreadonly DEFAULT_TMPDIR=/tmp\nreadonly DEFAULT_USERDATA_KEY=snapraid-btrfs\nreadonly E_MISSING_DEPENDENCY=63\nreadonly E_INTERNAL_ERROR=64\nreadonly E_INVALID_ARGUMENT=65\nreadonly E_INVALID_CONFIG=66\nreadonly E_NO_PERMISSION=67\nreadonly E_SNAPSHOT_NOT_FOUND=68\nreadonly E_INTERACTIVE_NO=69\n# for use with awk\n# mawk versions < 1.3.4 don't support [:lower:],\n# so we use [$LOWER] instead for portability\nreadonly LOWER=abcdefghijklmnopqrstuvwxyz\nreadonly MY_VERSION='0.14.1+git'\n# snapraid short options, sorted by whether or not they accept arguments\nreadonly SNAPRAID_OPTS_ARG=BCLScdfilop\nreadonly SNAPRAID_OPTS_NOARG=DEFGHLNRTUVZaehmqv\n\n# bash version 4+ required for associative arrays, coprocesses, and\n# ;& and ;;& terminators in case statements\n# 4.1+ required for ACL support, <{var} fd variable assignment, and\n# BASH_XTRACEFD\nif [ -z \"${BASH_VERSION-}\" ] ||\n       ! { ((BASH_VERSINFO[0] > 4)) ||\n               { ((BASH_VERSINFO[0] == 4)) && ((BASH_VERSINFO[1] >= 1)) ; } ; }\nthen\n    echo 'bash version 4.1+ is required to use this script' >&2\n    exit ${E_MISSING_DEPENDENCY:-63}\nfi\n\nset -o errexit\nset -o errtrace\nset -o functrace\nset -o noglob\nset -o nounset\nset -o pipefail\nset +o noclobber\nset +o posix\nshopt -s dotglob\nshopt -s extglob\nshopt -s extquote\nshopt -s nullglob\n# Use lastpipe if available (bash 4.2+) since it's faster,\n# but we don't need the behavior\nshopt -s lastpipe &> /dev/null || true\n\n# Add $1 to snapper_configs_specified array if not duplicate\nadd_snapper_config() {\n    [[ \"${snapper_configs_specified_seen[$1]+x}\" ]] ||\n        snapper_configs_specified+=( \"$1\" )\n    snapper_configs_specified_seen[$1]=1\n}\n\n# Apply the --pre-post and --no-pre-post command line options\napply_pre_post_options() {\n    local i j\n    if ((${#pre_post_option[@]} > 0)) ; then\n        for i in \"${pre_post_option[@]}\" ; do\n            config_must_exist \"$i\"\n        done\n        pre_post_configs=( \"${pre_post_option[@]}\" )\n    else\n        pre_post_configs=( \"${snapper_configs[@]}\" )\n    fi\n    if ((${#no_pre_post_option[@]} > 0)) ; then\n        local -a temp_array\n        for i in \"${no_pre_post_option[@]}\" ; do\n            config_must_exist \"$i\"\n            temp_array=()\n            for j in \"${pre_post_configs[@]}\" ; do\n                [[ \"$j\" = \"$i\" ]] || temp_array+=( \"$j\" )\n            done\n            pre_post_configs=( \"${temp_array[@]}\" )\n        done\n    fi\n}\n\n# apply the --snapper-configs-file command line option\napply_snapper_configs_file_option() {\n    [[ -r \"$1\" ]] ||\n        error $E_INVALID_CONFIG \"$1 is not a readable file\"\n    local config=\n    while IFS= read -r config || [[ \"$config\" ]] ; do\n        add_snapper_config \"$config\"\n    done < \"$1\"\n}\n\n# apply the --snapper-configs command line option\napply_snapper_configs_option() {\n    local -a configs\n    IFS=',' read -r -a configs <<< \"$1\"\n    local i\n    for i in \"${configs[@]}\" ; do\n        add_snapper_config \"$i\"\n    done\n}\n\n# Set use_snapshot from comma-separated key=value pairs specified in $1\napply_use_snapshot_option() {\n    local -a args\n    local config config_using i\n    IFS=',' read -r -a args <<< \"$1\"\n    for i in \"${args[@]}\" ; do\n        IFS='=' read -r config config_using <<< \"$i\"\n        config_must_exist \"$config\"\n        use_snapshot[$config]=\"$config_using\"\n    done\n}\n\n# Prints a function call stack, not including itself\ncall_stack() {\n    local func line script\n    local -i frame=1\n    echo 'Call stack:'\n    while IFS=' ' read -r line func script ; do\n        printf -- '%s: %s: %s\\n' \"$script\" \"$func\" \"$line\"\n    done < <(while caller $frame ; do ((++frame)) ; done)\n}\n\n# Sanity checks to run after reading configuration from\n# snapraid.conf and snapper list-configs\ncheck_config() {\n    if ((${#snapper_configs[@]} > 0)) ; then\n        check_content_files\n        check_snapper_configs\n    else\n        error_nonshell \"$1\" $E_INVALID_CONFIG \\\n            \"No snapper configs found for any data drives in $config_file\"\n    fi\n}\n\n# Sanity checks to run before reading snapraid.conf file\ncheck_config_file() {\n    if ! [[ -r \"$config_file\" ]] ; then\n        error_nonshell \"$1\" $E_INVALID_ARGUMENT \\\n            \"Could not read snapraid config file at $config_file\"\n        return 0\n    fi\n    verbose \"Using snapraid config file $config_file\"\n    # check for trailing newline in snapraid.conf\n    # Lack of a trailing newline will cause problems.\n    # Therefore, if there is no trailing newline, create a\n    # temporary config file with a newline added and use that instead.\n    if [[ \"$(tail -c 1 \"$config_file\")\" ]] ; then\n        warn \"No newline at end of $config_file\"\n        local new_config_file\n        new_config_file=\"$(mktemp -- \"$temp_dir/$my_name.XXXXXX\")\"\n        rm_on_exit+=( \"$new_config_file\" )\n        cat < \"$config_file\" > \"$new_config_file\"\n        echo >> \"$new_config_file\"\n        config_file=\"$new_config_file\"\n    fi\n}\n\n# We don't want to snapshot the content files. So, check the\n# directories of the content files, and compare their mount points with\n# those of the subvolumes we are snapshotting, to see if any match\ncheck_content_files() {\n    local field1 field2 content_dir content_mount i\n    while IFS=$' \\t' read -r field1 field2 ; do\n        if [[ \"$field1\" = content ]] ; then\n            if [[ -f \"$field2\" ]] ; then\n                content_dir=\"$(dirname -- \"$field2\")\"\n                if [[ -d \"$content_dir\" ]] ; then\n                    content_mount=\"$(stat --format=%m -- \"$content_dir\")\"\n                    for i in \"${snapper_configs[@]}\" ; do\n                        if [[ \"$content_mount\" -ef \\\n                            \"${snapper_subvols[$i]}\" ]]\n                        then\n                            error $E_INVALID_CONFIG \\\n                                \"$field2 found in subvolume\" \\\n                                \"${snapper_subvols[$i]}\" \\\n                                '- content files must be in separate subvolume'\n                        fi\n                    done\n                else\n                    warn \"content directory $content_dir not found\"\n                fi\n            else\n                warn \"content file $field2 not found\"\n            fi\n        fi\n    done < \"$config_file\"\n}\n\n# Make sure all external binaries in $@ can be found\ncheck_dependencies() {\n    while (($# > 0)) ; do\n        if ! type \"$1\" &> /dev/null ; then\n            error $E_MISSING_DEPENDENCY \"Could not find dependency $1\"\n        fi\n        shift\n    done\n}\n\ncheck_snapper_configs() {\n    local i\n    for i in \"${snapper_configs[@]}\" ; do\n        # Check that .snapshots subvolume exists\n        if ! is_btrfs_subvolume \"${snapper_subvols[$i]}/.snapshots\" ; then\n            error $E_INVALID_CONFIG \"${snapper_subvols[$i]}/.snapshots\" \\\n                'is not a valid btrfs subvolume'\n        # Check that we have read permission for the .snapshots subvolume\n        # If not, try running snapper ls, in case ACLs need to be synced\n        elif ! { [[ -r \"${snapper_subvols[$i]}/.snapshots\" ]] ||\n                     { snapper_ls_sync_acl \"$i\" &&\n                           [[ -r \"${snapper_subvols[$i]}/.snapshots\" ]] ; } ; }\n        then\n            error $E_NO_PERMISSION 'No read permission for' \\\n                \"${snapper_subvols[$i]}/.snapshots\" \\\n                '- is SYNC_ACL set in snapper configuration?'\n        fi\n    done\n}\n\n# Make sure the user hasn't tried to pass through the -c option to snapraid\ncheck_snapraid_arguments() {\n    while (($# > 0)) ; do\n        case $1 in\n            --)\n                break ;;\n            --conf|-*([\"$SNAPRAID_OPTS_NOARG\"])c*)\n                error $E_INVALID_ARGUMENT \\\n                    \"The -c/--conf option can't be passed through to snapraid\"\n                ;;\n        esac\n        if snapraid_opt_has_arg \"$@\" ; then\n            shift 2\n        else\n            shift\n        fi\n    done\n}\n\ncleanup_coproc_debug() {\n    [[ \"${debug_fd}\" ]] || return 0\n    trap - DEBUG\n    eval \"${debug_fd:+exec ${debug_fd}>&-}\"\n    eval \"${sed_escape_debug[1]:+exec ${sed_escape_debug[1]}>&-}\"\n    # shellcheck disable=2154\n    # Shellcheck doesn't understand named coprocesses\n    # See https://github.com/koalaman/shellcheck/issues/1066\n    eval \"${sed_escape_debug_PID:+wait $sed_escape_debug_PID}\"\n    debug_fd=\n}\n\ncleanup_coproc_xtrace() {\n    [[ \"${xtrace_fd}\" ]] || return 0\n    set +o xtrace\n    BASH_XTRACEFD=\"${xtrace_fd_old:-2}\"\n    eval \"${xtrace_fd:+exec ${xtrace_fd}>&-}\"\n    eval \"${sed_escape_xtrace[1]:+exec ${sed_escape_xtrace[1]}>&-}\"\n    # shellcheck disable=2154\n    # Shellcheck doesn't understand named coprocesses\n    # See https://github.com/koalaman/shellcheck/issues/1066\n    eval \"${sed_escape_xtrace_PID:+wait $sed_escape_xtrace_PID}\"\n    xtrace_fd=\n    xtrace_fd_old=\n}\n\ncleanup_coprocs() {\n    cleanup_coproc_debug\n    cleanup_coproc_xtrace\n}\n\n# Run snapper rm on config $1, with $2, $3, ... specifying snapshots to delete\ncleanup_snapshots() {\n    if (($# < 2)) ; then\n        return 0\n    fi\n    local config=\"$1\"\n    shift\n    local -i ret\n    if ((interactive > 0)) ; then\n        snapper_ls_wrapper \"$config\" >&2\n        echo >&2\n    fi\n    verbose_command_run \"$my_snapper\" -c \"$config\" \\\n        rm${sync:+ --sync} \"$@\" && true\n    ret=$?\n    if ((interactive > 0)) ; then\n        echo >&2\n    fi\n    return $ret\n}\n\n# Check that the user didn't specify a nonexistent snapper config by ensuring\n# that a subvolume is set for the config name\nconfig_must_exist() {\n    [[ \"${snapper_subvols[$1]-}\" ]] ||\n        error $E_INVALID_ARGUMENT \"Invalid snapper configuration $1\"\n}\n\n# Calling once creates pre snapshots, calling again creates corresponding post\ncreate_pre_post_snapshots() {\n    local -a snapper_cmd\n    local post_snapshot i\n    for i in \"${pre_post_configs[@]}\" ; do\n        # skip configs where we're using a readonly snapshot\n        [[ \"${use_snapshot[$i]}\" = 0 ]] || continue\n        snapper_cmd=( \"$my_snapper\" -c \"$i\" create )\n        if [[ \"$snapper_cleanup\" ]] ; then\n            snapper_cmd+=( -c \"$snapper_cleanup\" )\n        fi\n        # Check if we've already done a pre snapshot\n        if [[ \"${pre_snapshot[$i]-}\" ]] ; then\n            # We've already done pre snapshots, so create corresponding post\n            if [[ \"$snapper_description\" ]] ; then\n                snapper_cmd+=( -d \"$snapper_description\" )\n            else\n                snapper_cmd+=( -d \"$my_name post-$1\" )\n            fi\n            snapper_cmd+=(\n                -u \"$snapper_userdata$snapper_userdata_key=post-$1\"\n                -t post\n                --pre-number \"${pre_snapshot[$i]}\"\n                -p\n            )\n            if post_snapshot=\"$(\"${snapper_cmd[@]}\")\" ; then\n                verbose \"Created post snapshot\" \\\n                    \"${snapper_subvols[$i]}/.snapshots/$post_snapshot\"\n            else\n                warn \"Failed to create post snapshot for pre snapshot\" \\\n                    \"${snapper_subvols[$i]}/.snapshots/${pre_snapshot[$i]}\"\n            fi\n        else\n            # We haven't created pre snapshots yet, so create them and store\n            # the snapshot numbers from snapper -p option in ${pre_snapshot[@]}\n            if [[ \"$snapper_description\" ]] ; then\n                snapper_cmd+=( -d \"$snapper_description\" )\n            else\n                snapper_cmd+=( -d \"$my_name pre-$1\" )\n            fi\n            snapper_cmd+=(\n                -u \"$snapper_userdata$snapper_userdata_key=pre-$1\"\n                -t pre\n                -p\n            )\n            pre_snapshot[$i]=\"$(\"${snapper_cmd[@]}\")\"\n            verbose \"Created pre snapshot\" \\\n                \"${snapper_subvols[$i]}/.snapshots/${pre_snapshot[$i]}\"\n        fi\n    done\n}\n\n# display current state of variables\n# DEBUG is trapped in enable_debug_mode()\ndebug_trap() {\n    local -r div='----------------------------------------'\n    printf -- '%s\\n%s: %s%s\\n' \"$div\" \"$1\" \"$3\" \"$2\"\n    shift 3\n    call_stack\n    printf -- '%s\\n%s' \"$div\" 'set -- '\n    print_array \"$@\"\n    declare -p \"${debug_vars[@]}\"\n    printf -- '%s\\n' \"$div\"\n} >&\"$debug_fd\"\n\n# get variable names to pass as arguments to declare -p\ndeclare-p_vars() {\n    declare -p | declare-p_vars_awk \"$@\"\n}\n\ndeclare-p_vars_awk() {\n    local args\n    printf -v args -- '%s|' \"$@\"\n    args=\"${args%|}\"\n    awk -f <(cat <<_EOF_\nBEGIN {\n    FS = \"[ \\t=]+\"\n    ORS = \" \"\n}\n/^declare -[-Aair]+ ($args)/ {\n    print \\$3\n}\n_EOF_\n            )\n}\n\ndeclare-p_vars_debug() {\n    declare-p_vars \"[$LOWER]\" 'BASH' \\\n        '(DEBUG_FD|FUNCNAME|IFS|MY_VERSION|PIPESTATUS|TMPDIR)='\n}\n\ndeclare-p_vars_shell() {\n    declare-p_vars \"[_$LOWER]\" 'LOWER=' '(COPYRIGHT|DEFAULT|E|MY|SNAPRAID)_'\n}\n\n# In each config, delete snapshots with userdata key $snapper_userdata_key\n# older than use_snapshot[$i], or all such snapshots if use_snapshot[$i]=0\ndo_cleanup() {\n    local i j\n    local -i ret=0\n    local -i snapper_ret\n    local -a snapshots_to_consider snapshots_to_delete\n    for i in \"${snapper_configs[@]}\" ; do\n        # skip this config if we couldn't find a synced snapshot\n        if [[ -z \"${use_snapshot[$i]}\" ]] ; then\n            warn \"No synced snapshot found for config $i - skipping\"\n            continue\n        fi\n        IFS=' ' read -r -a snapshots_to_consider \\\n            <<< \"$(snapper_ls_wrapper \"$i\" 'C' |\n            parse_snapper_ls \"$snapper_userdata_key\" '' ' ')\"\n        snapshots_to_delete=()\n        for j in \"${snapshots_to_consider[@]}\" ; do\n            if [[ \"${use_snapshot[$i]}\" -gt \"$j\" ]] ||\n                   [[ \"${use_snapshot[$i]}\" = 0 ]]\n            then\n                snapshots_to_delete+=( \"$j\" )\n            fi\n        done\n        cleanup_snapshots \"$i\" \"${snapshots_to_delete[@]}\" && true\n        snapper_ret=$?\n        if ((snapper_ret != 0)) ; then\n            ret=$snapper_ret\n        fi\n    done\n    return $ret\n}\n\n# start interactive shell in context of script\ndo_shell() {\n    cleanup_coprocs\n    (\n        # shellcheck disable=2030\n        rm_on_exit=()\n        local _funcs _vars\n        local -a _funcs_arr _vars_arr\n        _funcs=\"$(declare -F |\n            awk -v ORS=' ' \"/^declare -f [$LOWER]/{print \\$3}\")\"\n        IFS=' ' read -r -a _funcs_arr <<< \"$_funcs\"\n        IFS=' ' read -r -a _vars_arr <<< \"$(declare-p_vars_shell)\"\n        _vars=\"$(declare -p \"${_vars_arr[@]}\")\"\n        export BASHOPTS SHELLOPTS _funcs _vars\n        export -f \"${_funcs_arr[@]}\"\n        set +o errexit\n        set +o nounset\n        exec \"$BASH\" --rcfile \\\n            <(cat <<'_EOF_'\neval \"$_vars\"\nexport -fn \"${_funcs_arr[@]}\"\nexport -n BASHOPTS SHELLOPTS\nunset -v _funcs _vars _funcs_arr _vars_arr\ntrap 'exit_trap' EXIT\nexit() {\n    printf -- 'Hooked exit command with status %s\\n' \"${1:-$?}\"\n    printf -- 'Use quit to exit the %s interactive shell\\n' \"$my_name\"\n}\nquit() {\n    command exit \"${@:-0}\"\n}\nvars() {\n    local -a _vars_arr\n    IFS=' ' read -r -a _vars_arr <<< \"$(declare-p_vars_debug)\"\n    declare -p \"${_vars_arr[@]}\"\n}\nif [[ -e \"$HOME/.bashrc\" ]] ; then\n    source \"$HOME/.bashrc\"\nfi\nif ((verbose >= 0)) ; then\n    cat <<__EOF__\nStarted interactive bash session in $my_name context.\nCommands:\n    quit - exit the interactive shell\n    vars - display variable values\n\n__EOF__\nfi\n_EOF_\n             ) -O extglob -i \"$@\"\n    )\n}\n\n# run the specified snapper command on each config\ndo_snapper() {\n    local i\n    for i in \"${snapper_configs[@]}\" ; do\n        if [[ \"${use_snapshot[$i]}\" = 0 ]] ; then\n            continue\n        else\n            verbose_command_run \"$my_snapper\" -c \"$i\" \"$@\"\n        fi\n    done\n}\n\n# Set DEBUG trap to display variables with each command\nenable_debug_mode() {\n    IFS=' ' read -r -a debug_vars <<< \"$(declare-p_vars_debug)\"\n    cleanup_coproc_debug\n    local debug_out_fd\n    if [[ \"$debug_file\" ]] ; then\n        exec {debug_out_fd}>\"$debug_file\"\n    else\n        debug_out_fd=\"${DEBUG_FD:-2}\"\n    fi\n    coproc sed_escape_debug {\n        sed_escape_output\n    } >&\"${debug_out_fd}\"\n    exec {debug_fd}<&\"${sed_escape_debug[1]}\"\n    # shellcheck disable=1004\n    trap 'debug_trap \"$LINENO\" \"$BASH_COMMAND\" \\\n        \"${FUNCNAME[0]:+${FUNCNAME[0]}(): }\" \"$@\"' DEBUG\n}\n\nenable_debug_modes() {\n    if ((debug_mode > 0)) ; then\n        enable_debug_mode\n    fi\n    if ((xtrace_mode > 0)) ; then\n        enable_xtrace_mode\n    fi\n}\n\n# Use sed coproc to escape BASH_XTRACEFD\nenable_xtrace_mode() {\n    cleanup_coproc_xtrace\n    local xtrace_out_fd\n    if [[ \"$xtrace_file\" ]] ; then\n        exec {xtrace_out_fd}>\"$xtrace_file\"\n    else\n        xtrace_out_fd=\"${BASH_XTRACEFD:-2}\"\n    fi\n    xtrace_fd_old=\"${BASH_XTRACEFD:-2}\"\n    coproc sed_escape_xtrace {\n        sed_escape_output\n    } >&\"${xtrace_out_fd}\"\n    exec {xtrace_fd}<&\"${sed_escape_xtrace[1]}\"\n    BASH_XTRACEFD=\"$xtrace_fd\"\n    set -o xtrace\n}\n\n# Intended to be called by ERR trap. Accepts the following arguments:\n# $1 - Line number where ERR condition occurred\n# $2 - Command that caused the ERR condition\n# $3 - Exit status that caused the ERR condition\nerr_trap() {\n    trap - DEBUG\n    printf -- '%s: %s: %s failed%s\\n' \"$my_name\" \"${1:-0}\" \\\n        \"${2:-unknown command}\" \"${3:+ with exit status $3}\"\n    call_stack\n    exit \"${3:-$E_INTERNAL_ERROR}\"\n} >&2\n\n# $1 - exit status to exit with\n# $2,$3,... - error message to print as $* after shifting\nerror() {\n    local -i errno=\"${1-}\"\n    if ((errno < 1)) || ((errno > 255)) ; then\n        printf -- 'error called with invalid exit status %s\\n' \"${1:-(none)}\"\n        errno=\"$E_INTERNAL_ERROR\"\n    fi\n    shift || true\n    printf -- '%s: ' \"$my_name\"\n    print_array \"${@:-fatal error}\"\n    case $errno in\n        \"$E_INVALID_ARGUMENT\")\n            printf -- 'Use %s -h for help\\n' \"$my_name\" ;;\n    esac\n    exit \"$errno\"\n} >&2\n\n# error if not running the shell command, otherwise warning\n# $1 - command being run\n# $2,$3,... - args to pass to error() if $1 != shell\nerror_nonshell() {\n    if ! { [[ \"$1\" =~ ^[a-z-]*$ ]] && [[ \"$2\" =~ ^[0-9]*$ ]] ; } ; then\n        error $E_INTERNAL_ERROR \\\n            'error_nonshell() called with invalid arguments'\n    elif [[ \"$1\" = 'shell' ]] ; then\n        shift 2\n        warn \"$@\" '- ignoring to start interactive shell'\n    else\n        shift\n        error \"$@\"\n    fi\n}\n\n# Intended to be called by EXIT trap\n# Removes rm_on_exit if nonempty and cleans up coprocess if necessary\nexit_trap() {\n    # shellcheck disable=2031\n    if ((${#rm_on_exit[@]} > 0)) ; then\n        rm -f -- \"${rm_on_exit[@]}\" || true\n    fi\n    cleanup_coprocs\n}\n\n# remove -h / --pre-hash from snapraid arguments\n# used with diff-sync command since -h is only supported with sync command\nfilter_pre_hash_option() {\n    local args=()\n    local i\n    for i in \"$@\" ; do\n        if [[ \"$i\" =~ !(-h|--pre-hash) ]] ; then\n            args+=( \"$i\" )\n        fi\n    done\n    print_array \"${args[@]}\"\n}\n\nfind_configs() {\n    if ((${#snapper_configs_specified[@]} > 0)) ; then\n        find_configs_specified\n    else\n        find_configs_snapper_get-config \"$@\"\n    fi\n}\n\n# if the user has specified --snapper-configs and/or --snapper-configs-file\n# command line options, use them to find snapper configs\nfind_configs_specified() {\n    local i\n    for i in \"${snapper_configs_specified[@]}\" ; do\n        find_configs_try \"$i\" && true\n        case $? in\n            1)\n                error $E_INVALID_CONFIG \\\n                    \"SUBVOLUME for config $i not found in $config_file\" ;;\n            2)\n                error $E_INVALID_CONFIG \\\n                    \"Failed to run snapper get-config for config $i\" ;;\n        esac\n    done\n    verbose\n}\n\n# try snapper get-config for all configs found in /etc/snapper/configs\n# and look for SUBVOLUME matching /etc/snapraid.conf\nfind_configs_snapper_get-config() {\n    local config dir i\n    local -a files\n    dir=\"${SNAPPER_CONFIG_DIR-$DEFAULT_SNAPPER_CONFIG_DIR}\"\n    if ! [[ -d \"$dir\" ]] ; then\n        error $E_INVALID_CONFIG \"$dir is not a directory\"\n    elif ! [[ -r \"$dir\" ]] ; then\n        error $E_NO_PERMISSION \"No read permission for $dir\"\n    fi\n    set +o noglob\n    files=( \"$dir\"/* )\n    set -o noglob\n    if ((\"${#files[@]}\" == 0)) ; then\n        error_nonshell \"$1\" $E_INVALID_CONFIG \"No files in $dir\"\n    fi\n    for i in \"${files[@]}\" ; do\n        config=\"$(basename -- \"$i\")\"\n        find_configs_try \"$config\" && true\n        case $? in\n            1)\n                verbose \\\n                    \"SUBVOLUME for config $config not found in $config_file\" ;;\n            2)\n                verbose \\\n                    \"Failed to run snapper get-config for config $config\" ;;\n        esac\n    done\n    verbose\n}\n\n# Try to find a match between the snapper config $1 and snapraid.conf and\n# add it to snapper_configs array if successful\n# return 0 if $1 matches snapraid.conf\n# return 1 if $1 doesn't match snapraid.conf\n# return 2 if we couldn't run snapper get-config for $1\nfind_configs_try() {\n    local config field1 field2 field3 found subvol\n    config=\"$1\"\n    found=\n    if subvol=\"$(\"$my_snapper\" -c \"$config\" get-config 2>/dev/null |\n        sed -e '/^SUBVOLUME /!d' -e 's/^SUBVOLUME[ ]*| //')\"\n    then\n        while IFS=$' \\t' read -r field1 field2 field3 ; do\n            if [[ \"$field1\" =~ ^(data|disk)$ ]] &&\n                   [[ \"$field3\" -ef \"$subvol\" ]]\n            then\n                found=1\n                snapper_configs+=( \"$config\" )\n                snapper_subvols[$config]=\"$subvol\"\n                snapraid_names[$config]=\"$field2\"\n            fi\n        done < \"$config_file\"\n        if [[ \"$found\" ]] ; then\n            verbose \\\n                \"Found $subvol in $config_file - using snapper config $config\"\n            return 0\n        else\n            return 1\n        fi\n    else\n        return 2\n    fi\n}\n\n# output the last snapshot number from config $1 matching userdata key $2\n# (or any if $2 is undefined or empty)\nfind_snapshot() {\n    snapper_ls_wrapper \"$1\" 'C' |\n        parse_snapper_ls \"$snapper_userdata_key\" \"${2:+$2}\" |\n        tail -n 1\n}\n\n# replace keywords in use_snapshot with actual snapshot numbers, or with the\n# empty string if a snapshot matching the keyword cannot be found\nfind_snapshots() {\n    local -i n=0\n    local i\n    for i in \"${snapper_configs[@]}\" ; do\n        use_snapshot_missing[$i]=\"${use_snapshot[$i]}\"\n        case ${use_snapshot[$i]} in\n            0|'')\n                continue ;;\n            diff)\n                use_snapshot[$i]=\"$(find_snapshot \"$i\" 'diff')\" ;;\n            last)\n                use_snapshot[$i]=\"$(find_snapshot \"$i\")\" ;;\n            menu)\n                snapshot_menu \"$i\" \"$1\" ;;\n            new)\n                new_snapshot \"$i\" \"$1\" ;;\n            res?(ume))\n                use_snapshot[$i]=\"$(find_snapshot \"$i\" 'syncing,synced')\" ;;\n            scrub)\n                use_snapshot[$i]=\"$(find_snapshot \"$i\" \\\n                    'syncing,synced,post-fix,post-touch')\" ;;\n            sync)\n                use_snapshot[$i]=\"$(find_snapshot \"$i\" 'synced')\" ;;\n            +([0123456789]))\n                if ! { snapper_ls_wrapper \"$i\" 'C' |\n                           parse_snapper_ls |\n                           grep -Fx \"${use_snapshot[$i]}\" > /dev/null ; }\n                then\n                    use_snapshot[$i]=\n                fi ;;\n            *)\n                error $E_INVALID_ARGUMENT \\\n                    'Could not understand snapshot selection' \\\n                    \"${use_snapshot[$i]} for config $i\" ;;\n        esac\n        if [[ \"${use_snapshot[$i]}\" ]] ; then\n            ((++n))\n            use_snapshot_missing[$i]=\n            if [[ \"${use_snapshot[$i]}\" = '0' ]] ; then\n                verbose \"Using live filesystem for config $i\"\n            else\n                verbose \"Using snapshot ${use_snapshot[$i]} for config $i\"\n            fi\n        fi\n    done\n    if ((n > 0)) ; then\n        verbose\n    fi\n}\n\n# generate sed script to replace subvolume paths with corresponding snapshots\n# (and pool directory, if --pool-dir is specified) and run it on snapraid.conf\ngenerate_temp_snapraid_conf() {\n    local match_line new_path sed_find sed_replace i\n    local sed_exps=()\n    # sed BRE matching data line up to the point where the path starts\n    local -r data_line=$'^[ \\t]*data[ \\t]\\{1,\\}[^ \\t]\\{1,\\}[ \\t]\\{1,\\}'\n    if [[ \"$pool_dir\" ]] ; then\n        sed_exps+=( $'/^[ \\t]*pool[ \\t]\\{1,\\}/d'\n                    \"\\$apool $pool_dir\" )\n    fi\n    for i in \"${snapper_configs[@]}\" ; do\n        if [[ \"${use_snapshot[$i]}\" != 0 ]] ; then\n            new_path=\"${snapper_subvols[$i]}/.snapshots/\"\n            new_path+=\"${use_snapshot[$i]}/snapshot\"\n            if ! is_btrfs_subvolume \"$new_path\" ; then\n                error $E_SNAPSHOT_NOT_FOUND \"Invalid snapshot $new_path\"\n            elif ! [[ -r \"$new_path\" ]] ; then\n                error $E_NO_PERMISSION \"No read permission for $new_path\"\n            fi\n            # Escape special characters in paths so that they can be\n            # passed to sed as literal strings\n            sed_find=\"$(sed_escape_bre <<< \"${snapper_subvols[$i]}\")\"\n            sed_replace=\"$(sed_escape_replacement <<< \"$new_path\")\"\n            match_line=\"$data_line$sed_find\"'\\/\\{0,1\\}$'\n            # also match the deprecated token 'disk' using separate sed\n            # expression to avoid depending on the GNU extension \\|\n            sed_exps+=( \"/$match_line/s/$sed_find/$sed_replace/\"\n                        \"/${match_line/data/disk}/s/$sed_find/$sed_replace/\" )\n        fi\n    done\n    if ((${#sed_exps[@]} == 0)) ; then\n        cat < \"$config_file\"\n    else\n        sed -f <(printf -- '%s\\n' \"${sed_exps[@]}\") -- \"$config_file\"\n    fi\n}\n\n# given the snapraid.conf name for a disk (e.g. d1 in disk d1 /foo/bar),\n# find the corresponding snapper config name, if any\nget_snapper_config_name() {\n    local i\n    for i in \"${snapper_configs[@]}\" ; do\n        if [[ \"$1\" = \"${snapraid_names[$i]}\" ]] ; then\n            printf -- '%s\\n' \"$i\"\n            break\n        fi\n    done\n}\n\nget_snapper_version() {\n    \"$my_snapper\" --version | sed -n '1s/^[^0123456789]*//p'\n}\n\ninteractive_ask() {\n    echo 'About to run the following command:'\n    print_array \"$@\"\n    local choice\n    while true ; do\n        read -r -p 'Do it [Y/N]? ' choice\n        case $choice in\n            [Yy]?([Ee][Ss]))\n                break ;;\n            [Nn]?([Oo]))\n                exit $E_INTERACTIVE_NO ;;\n            *)\n                echo 'Invalid choice. Please enter y or n.' ;;\n        esac\n    done\n} >&2\n\ninvalid_argument() {\n    error $E_INVALID_ARGUMENT \"Invalid argument $1\"\n}\n\n# Returns:\n# 0 if $1 is a btrfs subvolume\n# 1 if $1 is an \"empty subvolume\" inside a snapshot\n# 2 if $1 is an ordinary directory\n# 3 if $1 is not a directory\n# 4 if we couldn't determine the inode number with stat\nis_btrfs_subvolume() {\n    [[ -d \"$1\" ]] || return 3\n    case $(stat --format=%i -- \"$1\") in\n        256)\n            return 0 ;;\n        2)\n            return 1 ;;\n        '')\n            return 4 ;;\n        *)\n            return 2 ;;\n    esac\n}\n\nmain() {\n    check_dependencies awk basename cat dirname grep mktemp rm sed stat tail\n\n    # Declare \"global\" variables as local to main since they will be\n    # accessible from any functions called from main\n    # These variables are set during processing of command line arguments and\n    # snapraid/snapper configurations and are initialized to defaults here\n\n    # snapraid config file location\n    local config_file=\"${SNAPRAID_CONFIG_FILE:-$DEFAULT_CONFIG_FILE}\"\n    # fd to send debug output to if -X/--debug is enabled\n    local debug_fd=\n    # --debug-file option argument\n    local debug_file=\n    # indicates whether the -X/--debug option has been enabled\n    local -i debug_mode=0\n    # array storing variables to print in DEBUG trap\n    local debug_vars=()\n    # indicates whether the -i/--interactive option has been enabled\n    local -i interactive=0\n    # filename of script determined at runtime\n    local my_name\n    my_name=\"$(basename -- \"${BASH_SOURCE[0]}\")\"\n    # snapper/snapraid commands to use, can be specified with the\n    # --snapper-path and --snapraid-path command line options\n    local my_snapper=snapper\n    local my_snapraid=snapraid\n    # --pool-dir option argument\n    local pool_dir=\n    # list of snapper configs to create pre/post snapshots for\n    local pre_post_configs=()\n    # --pre-post option argument, after splitting\n    local pre_post_option=()\n    # --no-pre-post option argument, after splitting\n    local no_pre_post_option=()\n    # names of temp files to rm upon exiting\n    local rm_on_exit=()\n    # snapper cleanup algorithm to specify when creating new snapshots\n    local snapper_cleanup=\n    # names of all snapper configs that match snapraid.conf\n    local snapper_configs=()\n    # These associative arrays are indexed by snapper configs in the\n    # snapper_configs array, and hold the following data:\n    # number of pre snapshot created, to use when creating post\n    local -A pre_snapshot\n    # subvolume corresponding to the snapper config\n    local -A snapper_subvols\n    # snapraid disk name corresponding to the snapper config\n    local -A snapraid_names\n    # which snapshot should be used for the snapper config\n    local -A use_snapshot\n    # values of use_snapshot not found by find_snapshots()\n    local -A use_snapshot_missing\n    # indexes are configs specified with either the\n    # --snapper-configs or --snapper-configs-file options\n    # associative array used to track duplicates,\n    # regular array to preserve the order configs were specified\n    local snapper_configs_specified=()\n    local -A snapper_configs_specified_seen\n    # description to specify to snapper when creating new snapshots\n    local snapper_description=\n    # variable to be set if snapper ls supports --disable-used-space\n    # (version 0.6.0 or newer) and --used-space option was not specified\n    local snapper_ls_quota_disable=\n    # variable to be set if snapper ls supports --disable-used-space\n    # (version 0.6.0 or newer)\n    local snapper_ls_quota_support=\n    # snapper userdata key that will be specified to track created snapshots\n    # can be changed by setting the SNAPRAID_USERDATA_KEY environment variable\n    local \\\n        snapper_userdata_key=\"${SNAPRAID_USERDATA_KEY:-$DEFAULT_USERDATA_KEY}\"\n    # additional userdata to set, specified with the --snapper-userdata option\n    local snapper_userdata=\n    # variable to be set if -s/--sync option is specified\n    local sync=\n    # location of temporary snapraid.conf\n    local temp_config_file=\n    # directory to create temporary snapraid.conf file in\n    local temp_dir=\"${TMPDIR:-$DEFAULT_TMPDIR}\"\n    # --use-snapshot-all option argument\n    local use_snapshot_all_option=\n    # --use-snapshot option argument\n    local use_snapshot_option=\n    # variable to be set if --used-space option is specified\n    local -i used_space_option=0\n    # controls verbosity, incremented by -v/--verbose or\n    # decremented by -q/--quiet command line option\n    local -i verbose=0\n    # fd to send xtrace output to if -x/--xtrace is enabled\n    local xtrace_fd=\n    # backup of original BASH_XTRACEFD\n    local xtrace_fd_old=\n    # --xtrace-file option argument\n    local xtrace_file=\n    # indicates whether the -x/--xtrace option has been enabled\n    local -i xtrace_mode=0\n\n    trap 'err_trap $LINENO \"$BASH_COMMAND\" $?' ERR\n    trap 'exit_trap' EXIT\n\n    # Iterate through command line arguments and process snapraid-btrfs options\n    # until a command is reached, then run the specified command, passing\n    # through any remaining command line arguments appearing after the command\n\n    # These are genuinely local variables used for option processing\n    # and will be unset after use\n    local opt_str\n    local -i length i\n    local command=\n    while (($# > 0)) ; do\n        case $1 in\n            # matching a snapraid command means option processing is complete\n            # and any further options will be passed through to snapraid\n            check) ;&\n            diff) ;&\n            fix) ;&\n            pool) ;&\n            resume) ;&\n            scrub) ;&\n            ?(diff-|d)sync) ;&\n            touch) ;&\n            # Option processing is also complete for other commands which\n            # accept arguments\n            ls|list) ;&\n            shell) ;&\n            snapper) ;&\n            undochange)\n                break ;;\n            # support options specified either before or after the command\n            # for commands which don't invoke snapraid or accept argument\n            cleanup?(-all)) ;&\n            config) ;&\n            create)\n                if [[ -z \"$command\" ]] ; then\n                    command=\"$1\"\n                    shift\n                else\n                    invalid_argument \"$1 to command $command\"\n                fi ;;\n            # snapraid-btrfs options specified before command\n            # long form options that don't take arguments\n            --debug) ;&\n            --help) ;&\n            --?(non)interactive) ;&\n            --quiet) ;&\n            --sync) ;&\n            --used-space) ;&\n            --verbose) ;&\n            --version) ;&\n            --xtrace)\n                set_option \"$1\"\n                shift ;;\n            # long form options that require arguments\n            --conf?(=*)) ;&\n            --cleanup?(=*)) ;&\n            --@(debug|xtrace)-file?(=*)) ;&\n            --description?(=*)) ;&\n            --pool-dir?(=*)) ;&\n            --?(no-)pre-post?(=*)) ;&\n            --snapper-configs?(-file)?(=*)) ;&\n            --snapper-@(path|userdata)?(=*)) ;&\n            --snapraid-path?(=*)) ;&\n            --use-snapshot?(-all)?(=*))\n                # allow POSIX --argument option or --argument=option formats\n                opt_str=\"${1%%=*}\"\n                if [[ \"$opt_str\" = \"$1\" ]] ; then\n                    set_option \"$opt_str\" \"${2-}\"\n                    shift 2\n                else\n                    set_option \"$opt_str\" \"${1#\"${opt_str}=\"}\"\n                    shift\n                fi ;;\n            --*)\n                invalid_argument \"$1\" ;;\n            # allow POSIX-style combining of short options\n            -*)\n                opt_str=\"${1#-}\"\n                length=\"${#opt_str}\"\n                for ((i=0;i<length;i++)) ; do\n                    case ${opt_str:$i:1} in\n                        # short options that don't take arguments\n                        [VXhiqsvx])\n                            set_option \"-${opt_str:$i:1}\"\n                            if ((i == length-1)) ; then\n                                shift\n                            fi ;;\n                        # short options that require arguments\n                        [CUcdu])\n                            if ((i == length-1)) ; then\n                                set_option \"-${opt_str:$i:1}\" \"${2-}\"\n                                shift 2\n                            else\n                                set_option \"-${opt_str:$i:1}\" \\\n                                    \"${opt_str:$((i+1))}\"\n                                shift\n                                break\n                            fi ;;\n                        *)\n                            invalid_argument \"-${opt_str:$i:1}\" ;;\n                    esac\n                done ;;\n            *)\n                invalid_argument \"$1\" ;;\n        esac\n    done\n    # wait until after option parsing is complete to enable --debug/--xtrace\n    # to allow for --debug-file/--xtrace-file to be parsed first\n    enable_debug_modes\n    if [[ \"${command-}\" ]] ; then\n        set -- \"$command\"\n    fi\n    # done processing arguments, so unset truly local variables and run command\n    unset -v command length opt_str i\n    warn_if_root\n    if (($# > 0)) ; then\n        setup_config \"$@\"\n        run_command \"$@\"\n    else\n        error $E_INVALID_ARGUMENT \"No command specified\"\n    fi\n}\n\n# set $snapper_userdata_key userdata key to $1\nmodify_userdata() {\n    local i\n    local -i ret=0\n    local -i snapper_ret\n    for i in \"${snapper_configs[@]}\" ; do\n        [[ \"${use_snapshot[$i]}\" = 0 ]] && continue\n        \"$my_snapper\" -c \"$i\" modify -u \"$snapper_userdata_key=$1\" \\\n            \"${use_snapshot[$i]}\" && true\n        snapper_ret=$?\n        if ((snapper_ret != 0)) ; then\n            ret=$snapper_ret\n        fi\n    done\n    return $ret\n}\n\nmust_be_executable() {\n    [[ -x \"$1\" ]] ||\n        error $E_INVALID_ARGUMENT \"$1 is not an executable file\"\n}\n\nmust_be_writable_dir() {\n    [[ -d \"$1\" ]] ||\n        error $E_INVALID_ARGUMENT \"$1 is not a directory${2:+ - $2}\"\n    [[ -w \"$1\" ]] ||\n        error $E_NO_PERMISSION \"No write permission for $1${2:+ - $2}\"\n}\n\nmust_be_writable_file() {\n    if [[ -d \"$1\" ]] ; then\n        error $E_INVALID_ARGUMENT \"$1 is a directory, not a file\"\n    elif [[ -f \"$1\" ]] && ! [[ -w \"$1\" ]] ; then\n        error $E_NO_PERMISSION \"No write permission for $1\"\n    else\n        local dir\n        dir=\"$(dirname \"$1\")\"\n        must_be_writable_dir \"$dir\"\n    fi\n}\n\nnew_snapshot() {\n    local snapper_create_opts=(\n        -u \"$snapper_userdata$snapper_userdata_key=created\"\n    )\n    if [[ \"$snapper_cleanup\" ]] ; then\n        snapper_create_opts+=( -c \"$snapper_cleanup\" )\n    fi\n    if [[ \"$snapper_description\" ]] ; then\n        snapper_create_opts+=( -d \"$snapper_description\" )\n    else\n        snapper_create_opts+=( -d \"$my_name${2:+ $2}\" )\n    fi\n    use_snapshot[$1]=\"$(\"$my_snapper\" -c \"$1\" create -p \\\n        \"${snapper_create_opts[@]}\")\"\n    verbose \"Created new snapshot ${use_snapshot[$1]} for config $1\"\n}\n\n# call this to make sure $2 is defined when user specifies option requring it\noption_requires_argument() {\n    [[ \"${2-}\" ]] ||\n        error $E_INVALID_ARGUMENT \"Option $1 requires an argument\"\n}\n\n# use awk to parse piped snapper ls output and find snapshot numbers\n# matching the specified userdata constraints:\n# if $1 and $2 are nonempty, match snapshots with userdata key $1=$2\n# (multiple userdata values can be comma-separated in $2 to match any of them)\n# else if $1 is nonempty, match snapshots with userdata key $1 defined\n# else match all snapshots\n# if multiple snapshots match, separate their numbers with $3, or\n# if $3 is undefined or empty, separate the snapshot numbers with newlines\nparse_snapper_ls() {\n    awk -F '|' \\\n        -v key=\"${1-}\" \\\n        -v value=\"${2-}\" \\\n        -v ORS=\"${3:-$'\\n'}\" \\\n        -f <(cat <<'_EOF_'\n# create array of values to match from comma-separated variable\nBEGIN {\n    if (value != \"\") {\n        split(value,values,\",\")\n    }\n}\n# read column titles in header, so as to work with different versions of\n# snapper that reorder columns\nNR==1 {\n    for (i=1;i<=NF;i++) {\n        # remove padding spaces, then store column number indexed by title\n        gsub(/[ ]+/,\"\",$i)\n        column[$i] = i\n    }\n    # check to make sure we found columns labelled \"#\" and \"Userdata\"\n    if (column[\"#\"] == \"\" || column[\"Userdata\"] == \"\") {\n        printf(\"error: expected snapper ls column names not found\\n\",\n               \"/dev/stderr\")\n        exit 1\n    }\n}\n# snapshot data begin on line 3\nNR>=3 {\n    # remove nonnumeric characters (padding spaces, mount status) from #\n    gsub(/[^0123456789]+/,\"\",$column[\"#\"])\n    if (key == \"\") {\n        # match all snapshots\n        print $column[\"#\"]\n    } else {\n        # split userdata column into key=value pairs in case\n        # multiple userdata keys are defined for a snapshot\n        split($column[\"Userdata\"],pairs,\",\")\n        # construct an array 'userdata' whose indices we will search in\n        for (i in pairs) {\n            # remove padding spaces\n            gsub(/^[ ]+/,\"\",pairs[i])\n            gsub(/[ ]+$/,\"\",pairs[i])\n            if (value == \"\") {\n                # we don't care about the value of the userdata key, so\n                # split key=value pairs and store only the key\n                split(pairs[i],keys,\"=\")\n                userdata[keys[1]]\n            } else {\n                # we care about both halves of the userdata key=value\n                # pair, so store the whole key=value string\n                userdata[pairs[i]]\n            }\n        }\n        # find and print our matches\n        if (value == \"\") {\n            # match key only\n            if (key in userdata) {\n                print $column[\"#\"]\n            }\n        } else {\n            # match both key and value\n            for (i in values) {\n                if (key \"=\" values[i] in userdata) {\n                    print $column[\"#\"]\n                    break\n                }\n            }\n        }\n        # (portably) clear userdata before moving on to next snapshot\n        split(\"\",userdata)\n    }\n}\n_EOF_\n            )\n}\n\nprint_array() {\n    local ret=\n    if [[ \"$#\" -gt 0 ]] ; then\n        printf -v ret -- '%s ' \"$@\"\n        ret=\"${ret% }\"\n    fi\n    printf -- '%s\\n' \"$ret\"\n}\n\nprint_version() {\n    cat <<_EOF_\nsnapraid-btrfs $MY_VERSION\nCopyright (C) $COPYRIGHT_YEARS Alex deBeus\nLicense GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>\nThis is free software; you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.\n_EOF_\n}\n\n# Run the command given in $1\nrun_command() {\n    case $1 in\n        # Implementation of commands that don't invoke snapraid\n        cleanup?(-all))\n            do_cleanup ;;\n        config)\n            generate_temp_snapraid_conf ;;\n        ls|list)\n            shift\n            snapper_ls \"$@\" ;;\n        shell)\n            shift\n            do_shell \"$@\" ;;\n        snapper)\n            shift\n            do_snapper \"$@\" ;;\n        undochange)\n            shift\n            snapper_undochange \"$@\" ;;\n        # Implementation of commands that invoke snapraid\n        check|diff|fix|pool|scrub|sync|touch)\n            run_snapraid \"$@\" && true ;;\n        resume)\n            shift\n            run_snapraid sync \"$@\" && true ;;\n        @(d|diff-)sync)\n            if ((interactive < 0)) ; then\n                error $E_INVALID_ARGUMENT \\\n                    'diff-sync and --noninteractive are incompatible'\n            fi\n            shift\n            local -i diff_ret\n            # shellcheck disable=2046\n            run_snapraid diff $(filter_pre_hash_option \"$@\") && true\n            diff_ret=$?\n            # snapraid diff returns 2 if a sync is required\n            if ((diff_ret == 2)) ; then\n                ((++interactive))\n                run_snapraid sync --force-empty \"$@\" && true\n            else\n                exit $diff_ret\n            fi ;;\n    esac\n    exit\n}\n\n# Returns exit status of snapraid, postfix calls with '&& true' to avoid\n# triggering errexit if snapraid's return status is nonzero\n# Because errexit will not trigger within this function, we postfix anything\n# inside it which cannot fail with || err_trap to trigger ERR trap manually\nrun_snapraid() {\n    local -a snapraid_command\n    local -i ret\n    check_snapraid_arguments \"$@\"\n    if [[ -z \"${temp_config_file}\" ]] ; then\n        temp_config_file=\"$(mktemp -- \"$temp_dir/$my_name.XXXXXX\")\" ||\n            err_trap $LINENO mktemp $?\n        rm_on_exit+=( \"$temp_config_file\" )\n        generate_temp_snapraid_conf > \"$temp_config_file\" ||\n            err_trap $LINENO generate_temp_snapraid_conf $?\n        show_temp_snapraid_conf \\\n            \"Using temporary snapraid config file ${temp_config_file}:\" ||\n            err_trap $LINENO show_temp_snapraid_conf $?\n    elif ((verbose > 0)) ; then\n        show_temp_snapraid_conf \\\n            \"(Re)using temporary snapraid config file ${temp_config_file}:\" ||\n            err_trap $LINENO show_temp_snapraid_conf $?\n    fi\n    snapraid_command=( \"$my_snapraid\" -c \"$temp_config_file\" \"$@\" )\n    verbose_command \"${snapraid_command[@]}\"\n    case $1 in\n        fix|touch)\n            create_pre_post_snapshots \"$1\" ||\n                err_trap $LINENO create_pre_post_snapshots $? ;;\n        sync)\n            modify_userdata syncing ||\n                err_trap $LINENO modify_userdata $?\n            # set up a trap to track whether snapraid sync returned exit status\n            # 0 because it completed successfully, or because it was\n            # interrupted with ctrl-C, but was able to clean up before exiting\n            local -i interrupted=0\n            trap '((++interrupted)) ; trap - INT TERM QUIT' INT TERM QUIT ;;\n    esac\n    # Run snapraid\n    \"${snapraid_command[@]}\"\n    ret=$?\n    case $1 in\n        fix|touch)\n            create_pre_post_snapshots \"$1\" ||\n                err_trap $LINENO create_pre_post_snapshots $? ;;\n        diff)\n            # snapraid diff returns 0 if no changes, 2 if sync needed\n            if ((ret == 0)) || ((ret == 2)) ; then\n                modify_userdata \"$1\" ||\n                    err_trap $LINENO modify_userdata $?\n            fi ;;\n        sync)\n            trap - INT TERM QUIT\n            # don't mark sync as completed if INT/TERM/QUIT trap was triggered\n            if ((ret == 0)) && ((interrupted == 0)) ; then\n                modify_userdata synced ||\n                    err_trap $LINENO modify_userdata $?\n            fi ;;\n    esac\n    return $ret\n}\n\n# make input suitable to be used in sed BRE as fixed string\n# in sed BRE, outside a bracket expression, the following must be escaped:\n# . * $ ^ [ / \\\nsed_escape_bre() {\n    sed 's/[.*$^/\\[]/\\\\&/g'\n}\n\n# escape output containing the following literal nonprintable ASCII characters:\n# \\e \\r \\t\nsed_escape_output() {\n    sed -e $'s/\\e/\\e[7m\\\\\\\\e\\e[0m/g' \\\n        -e $'s/\\r/\\e[7m\\\\\\\\r\\e[0m/g' \\\n        -e $'s/\\t/\\e[7m\\\\\\\\t\\e[0m/g'\n}\n\n# make input suitable to be used in sed replacement text as fixed string\n# in sed replacement text, the following must be escaped:\n# & / \\\nsed_escape_replacement() {\n    sed 's/[&/\\]/\\\\&/g'\n}\n\n# $1 is option being set, $2 is argument. If no argument,\n# $2 can be either undefined or empty\nset_option() {\n    case $1 in\n        --conf) ;&\n        --cleanup) ;&\n        --@(debug|xtrace)-file) ;&\n        --description) ;&\n        --pool-dir) ;&\n        --?(no-)pre-post) ;&\n        --snapper-@(path|userdata)) ;&\n        --snapraid-path) ;&\n        --use-snapshot?(-all)) ;&\n        -[CUcdu])\n            option_requires_argument \"$@\" ;;&\n        -c|--conf)\n            config_file=\"$2\" ;;\n        -C|--cleanup)\n            snapper_cleanup=\"$2\" ;;\n        -d|--description)\n            snapper_description=\"$2\" ;;\n        -h|--help)\n            usage\n            exit ;;\n        -i|--interactive)\n            ((++interactive)) || true ;;\n        -q|--quiet)\n            ((--verbose)) || true ;;\n        -s|--sync)\n            sync=1 ;;\n        -u|--use-snapshot-all)\n            use_snapshot_all_option=\"$2\" ;;\n        -U|--use-snapshot)\n            use_snapshot_option=\"$2\" ;;\n        -v|--verbose)\n            ((++verbose)) || true ;;\n        -V|--version)\n            print_version\n            exit ;;\n        -x|--xtrace)\n            ((++xtrace_mode)) ;;\n        -X|--debug)\n            ((++debug_mode)) ;;\n        --debug-file)\n            must_be_writable_file \"$2\"\n            debug_file=\"$2\" ;;\n        --no-pre-post)\n            IFS=',' read -r -a no_pre_post_option <<< \"$2\" ;;\n        --noninteractive)\n            ((--interactive)) || true ;;\n        --pool-dir)\n            must_be_writable_dir \"$2\"\n            pool_dir=\"$2\" ;;\n        --pre-post)\n            IFS=',' read -r -a pre_post_option <<< \"$2\" ;;\n        --snapper-configs)\n            apply_snapper_configs_option \"$2\" ;;\n        --snapper-configs-file)\n            apply_snapper_configs_file_option \"$2\" ;;\n        --snapper-path)\n            must_be_executable \"$2\"\n            my_snapper=\"$2\" ;;\n        --snapper-userdata)\n            use_snapper_userdata \"$2\" ;;\n        --snapraid-path)\n            must_be_executable \"$2\"\n            my_snapraid=\"$2\" ;;\n        --used-space)\n            ((++used_space_option)) ;;\n        --xtrace-file)\n            must_be_writable_file \"$2\"\n            xtrace_file=\"$2\" ;;\n        *)\n            invalid_argument \"$1\" ;;\n    esac\n}\n\n# Called immediately after all command line options have been parsed to\n# read snapraid configuration file and initialize the arrays local to main()\n# which track the configuration\nsetup_config() {\n    must_be_writable_dir \"$temp_dir\" 'is TMPDIR set correctly?'\n    check_dependencies \"$my_snapper\" \"$my_snapraid\"\n    readonly my_snapper my_snapraid\n    if version_is_at_least \"$(get_snapper_version)\" '0.6.0' ; then\n        snapper_ls_quota_support=1\n        if ((used_space_option == 0)) ; then\n            snapper_ls_quota_disable=1\n        fi\n    fi\n    check_config_file \"$@\"\n    find_configs \"$@\"\n    show_configs\n    check_config \"$@\"\n    if [[ \"$use_snapshot_option\" ]] ; then\n        apply_use_snapshot_option \"$use_snapshot_option\"\n    fi\n    local i\n    if [[ \"$use_snapshot_all_option\" ]] ; then\n        for i in \"${snapper_configs[@]}\" ; do\n            [[ \"${use_snapshot[$i]-}\" ]] ||\n                use_snapshot[$i]=\"$use_snapshot_all_option\"\n        done\n    fi\n    apply_pre_post_options\n    case $1 in\n        check|pool|scrub|undochange)\n            use_snapshot_default scrub ;;&\n        cleanup)\n            use_snapshot_all sync ;;&\n        cleanup-all|touch)\n            use_snapshot_all 0 ;;&\n        config)\n            use_snapshot_default last ;;&\n        create|diff|?(d|diff-)sync)\n            use_snapshot_default new ;;&\n        fix)\n            use_snapshot_fix \"$@\" ;;&\n        resume)\n            use_snapshot_default resume ;;&\n        shell|snapper)\n            use_snapshot_default '' ;;&\n        !(cleanup-all|ls|list|snapper|touch))\n            find_snapshots \"$1\" ;;&\n        !(cleanup?(-all)|ls|list|shell|snapper|touch))\n            use_snapshot_check \"$1\" ;;\n    esac\n}\n\nshow_configs() {\n    ((verbose > 0)) || return 0\n    local i\n    echo 'Snapper configs found:'\n    for i in \"${snapper_configs[@]}\" ; do\n        printf -- '%s %s\\n' \"$i\" \"${snapper_subvols[$i]}\"\n    done\n    echo\n} >&2\n\nshow_temp_snapraid_conf() {\n    ((verbose >= 0)) || return 0\n    print_array \"$@\"\n    cat < \"$temp_config_file\" && echo\n} >&2\n\n# Do a snapper ls in all configs, and if argument(s) are specified,\n# additionally identify which snapshots we found with userdata\n# key $snapper_userdata_key matching the arguments\nsnapper_ls() {\n    local i j\n    for i in \"${snapper_configs[@]}\" ; do\n        printf -- '%s %s\\n' \"$i\" \"${snapper_subvols[$i]}\"\n        snapper_ls_wrapper \"$i\"\n        for j in \"$@\" ; do\n            printf -- 'Snapshots with userdata key %s=%s:\\n' \\\n                \"$snapper_userdata_key\" \"$j\"\n            snapper_ls_wrapper \"$i\" 'C' |\n                parse_snapper_ls \"$snapper_userdata_key\" \"$j\" ' '\n            echo\n        done\n        echo\n    done\n}\n\n# Run snapper ls > /dev/null on config $1 to sync ACLs, using\n# --disable-used-space option if supported by snapper version in use\nsnapper_ls_sync_acl() {\n    LC_ALL=C \"$my_snapper\" -c \"$1\" \\\n        ls${snapper_ls_quota_support:+ --disable-used-space} > /dev/null ||\n        error $E_NO_PERMISSION 'Failed to sync ACLs with snapper ls'\n}\n\n# Run snapper ls on config $1, using --disable-used-space option if supported\n# by snapper version in use and if --used-space option wasn't specified\n# if $2 is set, use LC_ALL=$2\nsnapper_ls_wrapper() {\n    if [[ \"${2-}\" ]] ; then\n        LC_ALL=\"$2\" \"$my_snapper\" -c \"$1\" \\\n            ls${snapper_ls_quota_disable:+ --disable-used-space}\n    else\n        \"$my_snapper\" -c \"$1\" \\\n            ls${snapper_ls_quota_disable:+ --disable-used-space}\n    fi\n}\n\n# Run snapper undochange in each snapper config to revert to the state at the\n# time ${use_snapshot[$i]} was created, creating snapshots before and after\nsnapper_undochange() {\n    local i\n    local -i ret=0\n    local -i snapper_ret\n    local undochange_files=()\n    local undochange_opts=()\n    create_pre_post_snapshots undochange\n    # ensure that -i option, if specified, appears before snapshots\n    # and any other arguments specified (except --) appear after snapshots\n    while (($# > 0)) ; do\n        case $1 in\n            --)\n                shift\n                break ;;\n            -i|--input)\n                if (($# > 1)) ; then\n                    undochange_opts+=( \"$1\" \"$2\" )\n                    shift 2\n                else\n                    undochange_files+=( \"$1\" )\n                    shift\n                fi ;;\n            *)\n                undochange_files+=( \"$1\" )\n                shift ;;\n        esac\n    done\n    undochange_files+=( \"$@\" )\n    for i in \"${snapper_configs[@]}\" ; do\n        if [[ \"${use_snapshot[$i]}\" = 0 ]] ; then\n            continue\n        else\n            verbose_command_run \"$my_snapper\" -c \"$i\" undochange \\\n                \"${undochange_opts[@]}\" \"${use_snapshot[$i]}..0\" -- \\\n                \"${undochange_files[@]}\"\n            snapper_ret=$?\n            if ((snapper_ret != 0)) ; then\n                ret=$snapper_ret\n            fi\n        fi\n    done\n    create_pre_post_snapshots undochange\n    return $ret\n}\n\n# returns 0 if $2 is an argument to $1, and 1 if not\nsnapraid_opt_has_arg() {\n    if (($# < 2)) ; then\n        return 1\n    fi\n    case $1 in\n        # snapraid long-form options that require arguments\n        --count) ;&\n        --error-limit) ;&\n        --filter?(-disk)) ;&\n        --gen-conf) ;&\n        --import) ;&\n        --log) ;&\n        --older-than) ;&\n        --percentage) ;&\n        --plan) ;&\n        --test-fmt) ;&\n        --test-force-@(autosave|scrub)-at) ;&\n        --test-import-content) ;&\n        --test-io-cache) ;&\n        --test-parity-limit) ;&\n        --test-run) ;&\n        # snapraid short-form options that require arguments\n        -*([\"$SNAPRAID_OPTS_NOARG\"])[\"$SNAPRAID_OPTS_ARG\"])\n            return 0 ;;\n    esac\n    return 1\n}\n\n# Display a menu of snapshots for config $1 using snapper ls, and\n# let the user pick which one to use\nsnapshot_menu() {\n    if ((interactive < 0)) ; then\n        error $E_SNAPSHOT_NOT_FOUND \\\n            'not displaying snapshot menu since --noninteractive'\n    fi\n    local choice\n    printf -- '%s %s\\n' \"$1\" \"${snapper_subvols[$1]}\"\n    snapper_ls_wrapper \"$1\"\n    while true ; do\n        read -r -p 'Enter a snapshot (0 for none, n for new, q to quit): ' \\\n            choice\n        case $choice in\n            [Qq]?([Uu][Ii][Tt]))\n                exit $E_INTERACTIVE_NO ;;\n            [Nn]?([Ee][Ww]))\n                new_snapshot \"$1\" \"$2\"\n                break ;;\n            +([0123456789]))\n                if [[ \"$choice\" = 0 ]] ||\n                       { snapper_ls_wrapper \"$1\" 'C' |\n                             parse_snapper_ls |\n                             grep -Fx \"$choice\" > /dev/null ; }\n                then\n                    use_snapshot[$1]=\"$choice\"\n                    break\n                else\n                    printf -- 'Snapshot %s not found\\n' \"$choice\"\n                fi ;;\n            *)\n                printf -- 'Invalid selection %s\\n' \"$choice\" ;;\n        esac\n    done\n    echo\n}\n\n#if snapshot not found for a config, prompt the user to choose a different one\nsnapshot_not_found() {\n    printf -- '%s: Snapshot %s not found for config %s at %s\\n' \"$my_name\" \\\n        \"${use_snapshot_missing[$1]}\" \"$1\" \"${snapper_subvols[$1]}\"\n    snapshot_menu \"$1\" \"$2\"\n} >&2\n\nusage() {\n    cat <<_EOF_\nUsage: $my_name [options] <command> [arguments]\n\nArguments appearing after the command are passed through to snapraid, while\nthe following options appearing before the command are interpreted by\n$my_name:\n\n  -h, --help                    Show this help\n  -V, --version                 Show version info\n  -c, --conf FILE               Specify location of snapraid config file\n                                (default $DEFAULT_CONFIG_FILE)\n  -C, --cleanup ARG             Specify snapper cleanup algorithm to set for\n                                any snapshots created (default none)\n  -d, --description ARG         Specify snapper description to set for any\n                                snapshots created\n  -i, --interactive             Ask before running snapraid or any potentially\n                                destructive snapper commands (when using the\n                                cleanup(-all), snapper, or undochange commands)\n  -q, --quiet                   Only show snapraid/snapper output and errors\n  -s, --sync                    Pass the --sync option to snapper rm (when\n                                using the cleanup(-all) command)\n  -u, --use-snapshot-all ARG    Use one of the following arguments:\n                                    diff  - Use last snapshot a diff was\n                                            completed with\n                                    last  - Use last snapshots created\n                                    menu  - Select the snapshot to use\n                                            interactively from a menu\n                                    new   - Create new snapshots\n                                    res   - Resume using snapshots from an\n                                            interrupted sync, or last completed\n                                            sync if more recent\n                                    scrub - Same as res, unless a fix/touch was\n                                            done more recently than sync, then\n                                            use post-fix/touch snapshot\n                                    sync  - Use last snapshots a successful\n                                            sync was completed with\n                                or specify the snapshot number (0 for the live\n                                filesystem, following snapper syntax)\n                                Default is:\n                                    'new' for diff|dsync|sync\n                                    'last' for config\n                                    'scrub' for all other readonly commands\n  -U, --use-snapshot ARG        Specify snapshots to use for specific snapper\n                                configurations, using the snapper config name\n                                followed by an equals sign. Multiple\n                                configurations should be separated by commas,\n                                e.g. 'config1=5,config2=last'. Overrides -u\n  -v, --verbose                 Increase verbosity of output\n  -x, --xtrace                  Enable bash xtrace\n  -X, --debug                   Enable debugging output\n  --debug-file FILE             File to save -X/--debug output to\n  --no-pre-post ARG             Don't create pre/post snapshots for the\n                                specified snapper configuration(s). Multiple\n                                configurations should be separated by commas.\n  --noninteractive              Never prompt the user on error, instead fail\n  --pool-dir DIR                Create pool symlinks in DIR (defaults to\n                                directory specified in snapraid config file)\n  --pre-post ARG                Create pre/post snapshots only for the\n                                specified snapper configuration(s). Multiple\n                                configurations should be separated by commas.\n  --snapper-configs ARG         Comma-separated list of snapper configs to\n                                try matching with snapraid.conf file instead\n                                of looking in $DEFAULT_SNAPPER_CONFIG_DIR.\n                                Can be specified multiple times.\n  --snapper-configs-file FILE   Newline-separated list of snapper configs to\n                                try matching with snapraid.conf file instead\n                                of looking in $DEFAULT_SNAPPER_CONFIG_DIR.\n                                Can be specified multiple times.\n  --snapper-path PATH           Path to the snapper executable (defaults to\n                                first found in PATH)\n  --snapper-userdata ARG        Specify snapper userdata to set for any\n                                snapshots created in addition to the\n                                $my_name attribute, which is set by\n                                default and cannot be changed. Argument should\n                                be in key=value format accepted by snapper,\n                                with multiple keys separated by commas (e.g.\n                                key1=value1,key2=value2)\n  --snapraid-path PATH          Path to the snapraid executable (defaults to\n                                first found in PATH)\n  --used-space                  Don't pass the --disable-used-space option to\n                                snapper ls.\n  --xtrace-file FILE            File to save -x/--xtrace output to\n\n  NOTE: The snapraid -c/--conf option will not work unless placed before the\n  command, allowing it to be interpreted as a $my_name option. Snapraid\n  will be run with a temporary configuration file, generated using whatever\n  snapraid.conf file is specified using the $my_name -c/--conf option\n  ($DEFAULT_CONFIG_FILE by default).\n\nCommands are either one of the following snapraid commands:\n  'check'|'diff'|'pool'|'scrub'|'sync':\n        Run the snapraid command given, replacing data drives in snapraid\n        config file that have corresponding snapper configs with read-only\n        snapshots.\n  'fix'|'touch':\n        Run the snapraid command given, creating a set of pre/post snapshots\n        before and after (for fix, if the snapraid -d/--filter-disk option is\n        specified, create pre/post snapshots only for the specified disk(s),\n        and use the 'scrub' snapshot for the rest (see -u option above)).\n\nor one of the following $my_name specific commands:\n  'config':\n        Show the modified snapraid config file that would be used, but don't\n        actually run snapraid.\n  'create':\n        Create a new snapshot for all snapper configs corresponding to data\n        drives found in snapraid config file.\n  'cleanup':\n        Delete all snapshots created by $my_name before the last one a\n        successful sync has been completed with.\n  'cleanup-all':\n        Delete all snapshots created by $my_name.\n  'dsync'|'diff-sync':\n        Create a new snapshot for all snapper configs found in snapraid config\n        file, do a snapraid diff, then sync. Implies --interactive option for\n        the sync operation. Uses --force-empty for the sync operation, since\n        the diff must be manually approved anyway.\n  'list'|'ls':\n        Run snapper ls for all snapper configs found in snapraid config file.\n        If an argument is given, also list which snapshots in each config were\n        identified as having snapper userdata key equal to the argument.\n  'resume':\n        Resume an interrupted sync, using the same set of snapshots.\n  'shell':\n        Start an interactive bash session in $my_name context. Useful for\n        testing and debugging.\n  'snapper':\n        Run the given snapper command in all configs, unless they are disabled\n        by --use-snapshot exampleconfig=0 - for example:\n           $my_name -U foo=0 snapper get-config\n        would run\n           snapper -c \"\\$i\" get-config\n        substituting \"\\$i\" for each snapper config matching the snapraid.conf\n        file, except foo.\n  'undochange':\n        Use snapper undochange to revert the array to the state it was in at\n        the time of the last successful sync (or another snapshot if the -u or\n        -U option is specified), creating pre/post snapshots. Arguments are\n        passed through to snapper undochange, including the snapper undochange\n        -i option.\n\nEnvironment variables:\n  DEBUG_FD -\n        File descriptor to send debug output to if -X/--debug is used. For\n        example, running \"DEBUG_FD=3 $my_name -Xh 3>/tmp/debug\" would\n        send debug output to /tmp/debug while displaying only the normal output\n        of \"$my_name -h\" on the console. If unset, the default behavior\n        is to send debug output to stderr.\n  SNAPPER_CONFIG_DIR -\n        Location of snapper config files. If unset, it defaults to\n        $DEFAULT_SNAPPER_CONFIG_DIR.\n  SNAPRAID_CONFIG_FILE -\n        Default location of the snapraid.conf file if -c/--conf option is not\n        used. If unset, it defaults to $DEFAULT_CONFIG_FILE.\n  SNAPRAID_USERDATA_KEY -\n        Snapper userdata key that is used to track snapshots. If unset, it\n        defaults to $DEFAULT_USERDATA_KEY.\n  TMPDIR -\n        Directory to create temporary snapraid.conf file in. If unset, it\n        defaults to $DEFAULT_TMPDIR.\n_EOF_\n}\n\n# Add key/value pairs from $1 to snapper_userdata, unless key is\n# $snapper_userdata_key\nuse_snapper_userdata() {\n    local key value i\n    local -a args\n    IFS=',' read -r -a args <<< \"$1\"\n    for i in \"${args[@]}\" ; do\n        IFS='=' read -r key value <<< \"$i\"\n        if [[ \"$key\" = \"$snapper_userdata_key\" ]] ; then\n            error $E_INVALID_ARGUMENT \\\n                \"Cannot set reserved userdata key $key\"\n        else\n            snapper_userdata+=\"$key=$value,\"\n        fi\n    done\n}\n\n# Set use_snapshot to $1 for all configs, overriding any previous values\nuse_snapshot_all() {\n    local i\n    for i in \"${snapper_configs[@]}\" ; do\n        use_snapshot[$i]=\"$1\"\n    done\n}\n\n# If use_snapshot[$i] is the empty string for any snapper config, indicating\n# that find_snapshots did not find a match, handle the error\nuse_snapshot_check() {\n    local i\n    for i in \"${snapper_configs[@]}\" ; do\n        [[ \"${use_snapshot[$i]}\" ]] || snapshot_not_found \"$i\" \"$1\"\n    done\n}\n\n# For any configs where use_snapshot is undefined or empty, set it to $1\nuse_snapshot_default() {\n    local i\n    for i in \"${snapper_configs[@]}\" ; do\n        if [[ -z \"${use_snapshot[$i]-}\" ]] ; then\n            use_snapshot[$i]=\"$1\"\n        fi\n    done\n}\n\n# When running a fix operation, parse the -d/--filter-disk snapraid option and\n# set ${use_snapshot[@]} accordingly\nuse_snapshot_fix() {\n    if [[ \"${1-}\" = fix ]] ; then\n        shift\n    else\n        error $E_INTERNAL_ERROR \\\n            'use_snapshot_fix() called with unexpected arguments:' \"$@\"\n    fi\n    local disk snapper_config_name\n    local -i disks_found=0\n    while (($# > 0)) ; do\n        disk=\n        case $1 in\n            --)\n                break ;;\n            --filter-disk=*)\n                disk=\"${1#--filter-disk=}\"\n                shift ;;\n            --filter-disk|-*([\"$SNAPRAID_OPTS_NOARG\"])d)\n                option_requires_argument \"$@\"\n                disk=\"$2\"\n                shift 2 ;;\n            -*([\"$SNAPRAID_OPTS_NOARG\"])d*)\n                disk=\"${1#*([\"$SNAPRAID_OPTS_NOARG\"])d}\"\n                shift ;;\n            -*)\n                if snapraid_opt_has_arg \"$@\" ; then\n                    shift 2\n                else\n                    shift\n                fi ;;\n            *)\n                error $E_INVALID_ARGUMENT \\\n                    'The following could not be interpreted as valid' \\\n                    'snapraid arguments:' $'\\n' \"$@\" ;;\n        esac\n        if [[ \"$disk\" ]] ; then\n            ((++disks_found))\n            snapper_config_name=\"$(get_snapper_config_name \"$disk\")\"\n            if [[ \"$snapper_config_name\" ]] ; then\n                # for disks we are fixing, use the live filesystem\n                if ! [[ \"${use_snapshot[$snapper_config_name]-}\" =~ ^0?$ ]]\n                then\n                    error $E_INVALID_ARGUMENT \\\n                        \"Must use live filesystem for $snapper_config_name\" \\\n                        'since it is being fixed, but' \\\n                        \"${use_snapshot[$snapper_config_name]} was specified\"\n                fi\n                use_snapshot[$snapper_config_name]=0\n            fi\n        fi\n    done\n    if ((disks_found > 0)) ; then\n        # for disks we are not fixing, use the 'scrub' snapshot\n        use_snapshot_default scrub\n    else\n        # snapraid fix --filter-disk option was not specified\n        # snapraid will try to fix all disks, so use the live filesystem\n        use_snapshot_default 0\n    fi\n}\n\nverbose() {\n    ((verbose > 0)) || return 0\n    print_array \"$@\"\n}\n\nverbose_command() {\n    if ((interactive > 0)) ; then\n        interactive_ask \"$@\"\n    elif ((verbose >= 0)) ; then\n        print_array \"$@\"\n    fi\n} >&2\n\nverbose_command_run() {\n    verbose_command \"$@\"\n    \"$@\" && true\n}\n\n# compares version numbers specified in $1 and $2\n# returns 0 if $1 >= $2\nversion_is_at_least() {\n    local -i i\n    local -a ver1 ver2\n    IFS='.' read -r -a ver1 <<< \"$1\"\n    IFS='.' read -r -a ver2 <<< \"$2\"\n    # if ver1 contains fewer components than ver2, pad with zeroes\n    for ((i=${#ver1[@]};i<${#ver2[@]};i++)) ; do\n        ver1[i]=0\n    done\n    # ensure version components are suitable for numeric comparison\n    for ((i=0;i<${#ver1[@]};i++)) ; do\n        ver1[i]=\"${ver1[i]##*([^0123456789])}\"\n        ver1[i]=\"${ver1[i]%%[^0123456789]*}\"\n    done\n    # iterate through version components until we find the first difference\n    for ((i=0;i<${#ver2[@]};i++)) ; do\n        if ((ver1[i] > ver2[i])) ; then\n            return 0\n        elif ((ver1[i] < ver2[i])) ; then\n            return 1\n        fi\n    done\n    # if we reach this point, ver1 and ver2 are the same\n    # (possibly with ver1 having extra components)\n    return 0\n}\n\nwarn() {\n    ((verbose >= 0)) || return 0\n    printf -- '%s: WARNING: ' \"$my_name\"\n    print_array \"$@\"\n} >&2\n\nwarn_if_root() {\n    [[ \"$EUID\" = 0 ]] || return 0\n    warn \"Running $my_name as root is not recommended\"\n    warn '(nor is running snapraid as root)'\n}\n\nif [[ \"$0\" = \"${BASH_SOURCE[0]}\" ]] ; then\n    main \"$@\"\nfi\n"
  }
]