├── .gitignore ├── LICENSE ├── README.md ├── etc ├── logrotate.d │ └── backup └── logwatch │ ├── conf │ ├── logfiles │ │ └── backup.conf │ └── services │ │ └── backup.conf │ ├── readme.md │ └── scripts │ ├── services │ └── backup │ └── shared │ └── sqfullstampanywhere └── root └── NCscripts ├── 503.html ├── backup.sh ├── excludeLocations.borg ├── nc_borg.details ├── nc_sql.details └── xtraLocations.borg /.gitignore: -------------------------------------------------------------------------------- 1 | # ignore log files 2 | *.log 3 | 4 | # ignore all vscode settings files 5 | .vscode/ 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | Copyright © 2007 Free Software Foundation, Inc. 4 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 5 | Preamble 6 | The GNU General Public License is a free, copyleft license for software and other kinds of works. 7 | The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. 8 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. 9 | To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. 10 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 11 | Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. 12 | For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. 13 | Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. 14 | Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. 15 | The precise terms and conditions for copying, distribution and modification follow. 16 | TERMS AND CONDITIONS 17 | 0. Definitions. 18 | "This License" refers to version 3 of the GNU General Public License. 19 | "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. 20 | "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. 21 | To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. 22 | A "covered work" means either the unmodified Program or a work based on the Program. 23 | To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. 24 | To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. 25 | An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 26 | 1. Source Code. 27 | The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. 28 | A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. 29 | The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. 30 | The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. 31 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. 32 | The Corresponding Source for a work in source code form is that same work. 33 | 2. Basic Permissions. 34 | All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. 35 | You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. 36 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 37 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 38 | No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. 39 | When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 40 | 4. Conveying Verbatim Copies. 41 | You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. 42 | You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 43 | 5. Conveying Modified Source Versions. 44 | You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: 45 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date. 46 | b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". 47 | c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. 48 | d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. 49 | A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 50 | 6. Conveying Non-Source Forms. 51 | You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: 52 | a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. 53 | b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. 54 | c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. 55 | d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. 56 | e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. 57 | A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. 58 | A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. 59 | "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. 60 | If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). 61 | The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. 62 | Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 63 | 7. Additional Terms. 64 | "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. 65 | When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. 66 | Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: 67 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or 68 | b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or 69 | c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or 70 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or 71 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or 72 | f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. 73 | All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. 74 | If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. 75 | Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 76 | 8. Termination. 77 | You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). 78 | However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. 79 | Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. 80 | Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 81 | 9. Acceptance Not Required for Having Copies. 82 | You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 83 | 10. Automatic Licensing of Downstream Recipients. 84 | Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. 85 | An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. 86 | You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 87 | 11. Patents. 88 | A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". 89 | A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. 90 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. 91 | In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. 92 | If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. 93 | If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. 94 | A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. 95 | Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 96 | 12. No Surrender of Others' Freedom. 97 | If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 98 | 13. Use with the GNU Affero General Public License. 99 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 100 | 14. Revised Versions of this License. 101 | The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 102 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. 103 | If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. 104 | Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 105 | 15. Disclaimer of Warranty. 106 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 107 | 16. Limitation of Liability. 108 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 109 | 17. Interpretation of Sections 15 and 16. 110 | If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS 111 | How to Apply These Terms to Your New Programs 112 | If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. 113 | To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. 114 | 115 | Copyright (C) 116 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 117 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 118 | You should have received a copy of the GNU General Public License along with this program. If not, see . 119 | Also add information on how to contact you by electronic and paper mail. 120 | If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: 121 | Copyright (C) 122 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 123 | This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. 124 | The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". 125 | You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . 126 | The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NextCloud Backup Using borgbackup 2 | 3 | **THIS SCRIPT IS NO LONGER ACTIVELY MAINTAINED. I DO NOT USE NEXTCLOUD OFTEN ANYMORE. IF YOU REALLY WANT ME TO DO AN UPDATE TO THIS SCRIPT, PLEASE CONTACT ME** 4 | 5 | This script automates backing up your NextCloud installation using borgbackup 6 | and a remote ssh-capable storage system. I suggest using rsync.net since they 7 | have great speeds and a special pricing structure for borgbackup/attic users 8 | ([details here](https://www.rsync.net/products/attic.html)). 9 | 10 | This script automates the following tasks: 11 | 12 | - Optionally copies a 503 error page to your webserver so users know when your 13 | server is unavailable due to backups being performed. The 503 file is removed 14 | when the backup is completed so users can login again 15 | - Dumps the NextCloud mySQL database and adds it to the backup 16 | - Handles entering and exiting NextCloud's maintenance mode to 'lock' accounts 17 | so changes are not made during the backup process 18 | - Allows you to specify additional files you want backed up 19 | - Allows you to specify files/directories to exclude from your backups (e.g. 20 | previews) 21 | - Runs 'borg prune' to make sure you are trimming old backups on your schedule 22 | - Creates a clear, easy to parse log file so you can keep an eye on your backups 23 | and any errors/warnings 24 | 25 | ## Contents 26 | - [Installation/copying](#installationcopying) 27 | - [Environment notes](#environment-notes) 28 | - [Why this script must be run as root](#why-this-script-must-be-run-as-root) 29 | - [Script parameters](#script-parameters) 30 | - [Required parameters](#required-parameters) 31 | - [NextCloud data directory: -d _/path/to/data/_](#nextcloud-data-directory--d-pathtodata) 32 | - [NextCloud webroot: -n _/path/to/nextcloud/_](#nextcloud-webroot--n-pathtonextcloud) 33 | - [webuser account: -u _accountName_](#webuser-account--u-accountname) 34 | - [Optional parameters](#optional-parameters) 35 | - [Path to 503 error page: -5 _/path/to/filename.html_](#path-to-503-error-page--5-pathtofilenamehtml) 36 | - [Path to borg details file: -b _/path/to/filename.file_](#path-to-borg-details-file--b-pathtofilenamefile) 37 | - [Desired log file location: -l _/path/to/filename.file_](#desired-log-file-location--l-pathtofilenamefile) 38 | - [Path to SQL details file: -s _/path/to/filename.file_](#path-to-sql-details-file--s-pathtofilenamefile) 39 | - [Verbose output from borg: -v (no arguments)](#verbose-output-from-borg--v-no-arguments) 40 | - [Path to webroot: -w _/path/to/webroot/_](#path-to-webroot--w-pathtowebroot) 41 | - [Borg details file](#borg-details-file) 42 | - [Protect your borg details file](#protect-your-borg-details-file) 43 | - [borg specific entries (lines 1-4)](#borg-specific-entries-lines-1-4) 44 | - [Line 1: Path to borg base directory](#line-1-path-to-borg-base-directory) 45 | - [Line 2: Path to SSH key for remote server](#line-2-path-to-ssh-key-for-remote-server) 46 | - [Line 3: Connection string to remote repo](#line-3-connection-string-to-remote-repo) 47 | - [Line 4: Password for borg repo/repo key](#line-4-password-for-borg-reporepo-key) 48 | - [additional files/directories to backup](#additional-filesdirectories-to-backup) 49 | - [exclusion patterns](#exclusion-patterns) 50 | - [prune timeframe options](#prune-timeframe-options) 51 | - [borg remote location](#borg-remote-location) 52 | - [Examples](#examples) 53 | - [SQL details file](#sql-details-file) 54 | - [Protect your sql details file](#protect-your-sql-details-file) 55 | - [503 functionality](#503-functionality) 56 | - [Conditional forwarding by your webserver](#conditional-forwarding-by-your-webserver) 57 | - [NGINX](#nginx) 58 | - [Apache](#apache) 59 | - [Disabling 503 functionality altogether](#disabling-503-functionality-altogether) 60 | - [Scheduling: Cron](#scheduling-cron) 61 | - [The log file](#the-log-file) 62 | - [Using Logwatch](#using-logwatch) 63 | - [Remember to rotate your logs](#remember-to-rotate-your-logs) 64 | - [Final notes](#final-notes) 65 | 66 | ## Installation/copying 67 | 68 | Once you've either cloned this git or downloaded the release file, simply copy 69 | the *'NCscripts'* folder to wherever you like. I suggest putting it in your 70 | *'/root'* directory since the root user must execute the script. If you edit 71 | the 503.html, nc_borg.details and nc_sql.details files in place, then you don't 72 | have to specify their locations when running the script. 73 | 74 | Remember to make the script executable! 75 | 76 | ```Bash 77 | chmod +x backup.sh 78 | ``` 79 | 80 | In addition, you can rename the script file to anything you like. The log file 81 | will use that same name by default when naming itself and any mention of this 82 | file in the logs will automatically use whatever name you choose to give it. 83 | 84 | ## Environment notes 85 | 86 | The script is designed to be easy to use but still be flexible enough to 87 | accommodate a wide range of NextCloud setups. I have tested it with NextCloud 88 | 13 and 14 using a standard LEMP setup (Debian Stretch, NGINX, mariaDB & PHP7). 89 | The script accepts several parameters to provide it with the settings it 90 | requires to function. In addition, it reads external plain-text files for SQL 91 | and borg settings so you don't have to weed through the script code to supply 92 | things like passwords. 93 | 94 | ## Why this script must be run as root 95 | 96 | This script must be run by the root user and will exit with an error if you try 97 | running it otherwise. This is because NextCloud's OCC command (needed to put 98 | NextCloud into maintenance mode) must be run as the web-user account and only 99 | the root account can switch users without needing to stop and ask for 100 | permission/passwords. 101 | 102 | ## Script parameters 103 | 104 | You can run the script with the *'-?'* parameter to access the built-in help 105 | which explains the parameters. However, the following is a more detailed 106 | explanation of each parameter and how to use them. 107 | **Note that any parameters needing a directory (webroot, nextcloud root, etc.) 108 | can be entered with or without the trailing '/' since it's stripped by the script 109 | anyways.** 110 | 111 | General usage: 112 | 113 | ```Bash 114 | /path/to/script/scriptname.sh -parameter argument -parameter argument ... 115 | ``` 116 | 117 | ### Required parameters 118 | 119 | #### NextCloud data directory: -d _/path/to/data/_ 120 | 121 | This is the full path to the location where NextCloud actually stores data. In 122 | a setup such as I recommend on my blog at 123 | [https://mytechiethoughts.com](https://www.mytechiethoughts.com), you would be 124 | using an entry such as *'/var/nc_data'*. This directory and all subdirectories 125 | are automatically included in the backup. 126 | 127 | #### NextCloud webroot: -n _/path/to/nextcloud/_ 128 | 129 | This is the directory in which NextCloud's php and html files are located. It 130 | is generally somewhere under your webroot directory. This is required so the 131 | script can find the 'OCC' command to invoke maintenance mode. 132 | 133 | #### webuser account: -u _accountName_ 134 | 135 | This is the account that NextCloud runs under via your webserver. This is 136 | almost always *'www-data'*. You would have to check your NGINX/Apache config to 137 | be sure. 'OCC' will not run as any other user thus, the script cannot 138 | enter/exit maintenance mode without knowing which user to emulate. 139 | 140 | ### Optional parameters 141 | 142 | #### Path to 503 error page: -5 _/path/to/filename.html_ 143 | 144 | The path to an html file for the script to copy to your webroot during the 145 | backup process. This file can be scanned by your webserver and a 503 error can 146 | be issued to users letting them know that your NextCloud is 'temporarily 147 | unavailable' while being backed up. A sample 503 page is included for you. 148 | 149 | If you remove the default file or the one you specify is missing, a warning will 150 | be issued by the script but, it will continue executing. More details on the 151 | 503 notification can be found later in the [503 functionality](#503-functionality) section of this 152 | document.\ 153 | **Default: _scriptpath/503.html_** 154 | 155 | #### Path to borg details file: -b _/path/to/filename.file_ 156 | 157 | This is a text file that lays out various borg options such as repo name, 158 | password, additional files to include, exclusion patters, etc. A sample file is 159 | included for your reference. More details, including the *required order* of 160 | entries can be found later in this document in the [borg details file](#borg-details-file) 161 | section.\ 162 | **Default: _scriptpath/nc_borg.details_** 163 | 164 | #### Desired log file location: -l _/path/to/filename.file_ 165 | 166 | If you have a particular place and filename you'd like this script to use for 167 | it's log, then you can specify it using this parameter. I would recommend 168 | *'/var/log/backup.log'*. By default, the script will name the log file 169 | *scriptname*.log and will save it in the same directory as the script itself.\ 170 | **Default: _scriptpath/scriptname.log_** 171 | 172 | #### Path to SQL details file: -s _/path/to/filename.file_ 173 | 174 | This is a text file containing the details needed to connect to NextCloud's SQL 175 | database. More information about the *required order* of entries can be found 176 | later in this document in the [sql details file](#sql-details-file) section.\ 177 | **Default: _scriptpath/nc_sql.details_** 178 | 179 | #### Verbose output from borg: -v (no arguments) 180 | 181 | By default, the script will ask borg to generate summary only output and record 182 | that in the script's log file. If you are running the backup for the first time 183 | or are troubleshooting, you may want a detailed output of all files and their 184 | changed/unchanged/excluded status from borg. In that case, specify the -v 185 | switch. **Note: This will make your log file very large very quickly since EVERY 186 | file being backed up is written to the log.** 187 | 188 | #### Path to webroot: -w _/path/to/webroot/_ 189 | 190 | This is the path to the directory your webserver is using as it's default root. 191 | In other words, this is the directory that contains the html files served when 192 | someone browses to your server. Depending on your setup, this might be the same 193 | as your NextCloud webroot. 194 | 195 | This is used exclusively for 503 functionality since the script has to know 196 | where to copy the 503 file. If you don't want to use this functionality, you 197 | can omit this parameter and the script will issue a warning and move on. More 198 | details can be found in the [503 functionality](#503-functionality) section later in this 199 | document. 200 | 201 | ## Borg details file 202 | 203 | This file contains all the data needed to access your borg remote data repo. 204 | Each line must contain specific information in a specific order or *needs to be 205 | blank if that data is not required*. The sample file includes this data and 206 | example entries. The file must have the following information in the following 207 | order: 208 | 209 | 1. path to borg base directory **(required)** 210 | 2. path to ssh private key for remote server **(required)** 211 | 3. connection string to remote repo **(required)** 212 | 4. password for borg repo/repo key **(required)** 213 | 5. path to file listing additional files/directories to backup 214 | 6. path to file containing borg-specific exclusion patterns 215 | 7. prune timeframe options 216 | 8. location of borg remote instance 217 | 218 | ### Protect your borg details file 219 | 220 | This file contains information on how to access and decrypt your borg repo, 221 | therefore, you **must** protect it. You should lock it out for everyone but 222 | your root user. Putting it in your root folder is not enough! Run the following 223 | commands to restrict access to the root user only (assuming filename is 224 | *'nc_borg.details'*): 225 | 226 | ```Bash 227 | chown root:root nc_borg.details # make root the owner 228 | chmod 600 nc_borg.details # restrict access to root only (read/write) 229 | ``` 230 | 231 | ### borg specific entries (lines 1-4) 232 | 233 | If you need help with these options, then you should consult the borg 234 | documentation or search my blog at 235 | [https://mytechiethoughts.com](https://mytechiethoughts.com) for borg. Here's a 236 | very brief overview: 237 | 238 | #### Line 1: Path to borg base directory 239 | 240 | This is primary directory on your local system where your borg configuration is 241 | located, **NOT* the path to your borg binary. The base directory contains the 242 | borg configuration, cache, security files and keys. 243 | 244 | #### Line 2: Path to SSH key for remote server 245 | 246 | This is the SSH key used to connect to your remote (backup) server where your 247 | borg repo is located. **This is NOT your borg repo key!** 248 | 249 | > Please note: If you are planning on executing this script via cron or some 250 | > other form of automation, it is *highly recommended* that you use an SSH key 251 | > **without** a password! SSH is designed such that passwords cannot simply be 252 | > passed to it via environment variables, etc. so this is something not easily 253 | > automated by a script such as this for security reasons. As such, your 254 | > computer will sit and wait for you to enter the password and will NOT execute 255 | > the actual backup portion of the script until the SSH key password is provided. 256 | > 257 | > If you really want/need to use an SSH key password, you will have to look into 258 | > somethign like GNOME keyring or SSH-agent to provide a secure automated way to 259 | > provide that password to SSH and allow this script to continue. 260 | > 261 | > In practice, SSH keys without passwords are still quite safe since the key 262 | > must still be known in order to connect and most keys are quite long. In 263 | > addition, they key only connects to the remote server, your actual information 264 | > within the borg repository is still encrypted and secured with both a key and 265 | > password. 266 | 267 | #### Line 3: Connection string to remote repo 268 | 269 | This is the full server and path required to connect to your borg repo on the 270 | remote server. Very often it is the in the form of: 271 | 272 | ``` 273 | user@servername.tld:repo-name/ 274 | ``` 275 | 276 | for rsync.net it is in the following form: 277 | 278 | ``` 279 | username@server-number.rsync.net:repo-name/ 280 | ``` 281 | 282 | #### Line 4: Password for borg repo/repo key 283 | 284 | This is the password needed to access and decrypt your *borg repo*. Assuming 285 | you set up your borg repo using recommended practices, this will actually be the 286 | password for your *borg repo private key*. **This is NOT your SSH key 287 | password!** 288 | 289 | ### additional files/directories to backup 290 | 291 | This points to a plain-text file listing additional files and directories you'd 292 | like borg to include in the backup. The sample file, *'xtraLocations.borg'* 293 | contains the most likely files you'd want to include assuming you're using a 294 | standard setup like it outline in my blog. 295 | 296 | The following would include all files in the home folder for users *'foo'* and 297 | *'bar'* and any conf files in *'/etc/someProgram'*: 298 | 299 | ```Bash 300 | /home/foo/ 301 | /home/bar/ 302 | /etc/someProgram/*.conf 303 | ``` 304 | 305 | You can leave this line blank to tell borg to only backup your NextCloud data 306 | directory and the SQL dump. However, this is pretty unusual since you would not 307 | be including any configuration files, webserver configurations, etc. If you 308 | omit this line, the script will log a warning to remind you of this unusual 309 | situation. 310 | 311 | ### exclusion patterns 312 | 313 | This points to a plain-text file containing borg-specific patterns describing 314 | what files you'd like borg to ignore during the backup. The sample file, 315 | *'excludeLocations.borg'* contains a list of directories to exclude assuming a 316 | standard NextCloud install -- the previews directory and the cache directory. 317 | You need to run *'borg help patterns'* for help on how to specify any additional 318 | exclusion patterns since the format is not standard BASH format and only 319 | sometimes uses standard regex. 320 | 321 | If you leave this line blank, the script will note it is not processing any 322 | exclusions and will proceed with backing up all files specified. 323 | 324 | ### prune timeframe options 325 | 326 | Here you can let borg prune know how you want to manage your backup history. 327 | Consult the borg documentation and then copy the relevant options directly into 328 | this line including any spaces, etc. The example file contains the following as 329 | a staring point: 330 | 331 | ```Ini 332 | --keep-within=7d --keep-daily=30 --keep-weekly=12 --keep-monthly=-1 333 | ``` 334 | 335 | This would tell borg prune to keep ALL backups made for any reason within the 336 | last 7 days, keep 30 days worth of daily backups, 12 weeks of end-of-week 337 | backups and then an infinite amount of end-of-month backups. 338 | 339 | ### borg remote location 340 | 341 | If you're using rsync, then just have this say *'borg1'*. If you are using 342 | another provider, you'll have to reference their locally installed copy of borg 343 | relative to your home directory. You can also leave this blank if your provider 344 | does not run borg locally but your backups/restores will be slower. 345 | 346 | ### Examples 347 | 348 | Repo in directory *'NCBackup'*, all fields including pointers to additional 349 | files to backup, exclusion patterns and a remote borg path. Prune: keep all 350 | backups made in the last 14 days. 351 | 352 | ```Ini 353 | /var/borgbackup 354 | /var/borgbackup/SSHprivate.key 355 | myuser@usw-s001.rsync.net:NCBackup/ 356 | myPaSsWoRd 357 | /root/NCscripts/xtraLocations.borg 358 | /root/NCscripts/excludeLocations.borg 359 | --keep-within=14d 360 | borg1 361 | ``` 362 | 363 | Repo in directory *'myBackup'*, no exclusions, keep 14 days end-of-day, 52 weeks 364 | end-of-week 365 | 366 | ```Ini 367 | /var/borgbackup 368 | /root/keys/rsyncPrivate.key 369 | myuser@usw-s001.rsync.net:myBackup/ 370 | PaSsWoRd 371 | /var/borgbackup/include.list 372 | 373 | --keep-daily=14 --keep-weekly=52 374 | borg1 375 | ``` 376 | 377 | Repo in directory *'backup'*, no extra file locations, no exclusions, no remote 378 | borg installation. Keep last 30 backups. 379 | 380 | ```Ini 381 | /root/.borg 382 | /root/.borg/private.key 383 | username@server.tld:backup/ 384 | pAsSw0rD 385 | 386 | 387 | --keep-within=30d 388 | 389 | ``` 390 | 391 | **Notice that the blank lines are very important!** 392 | 393 | ## SQL details file 394 | 395 | This file contains all the information needed to access your NextCloud SQL 396 | database in order to dump it's contents into a file that can be easily 397 | backed-up. Each line must contain specific information in a specific order. The 398 | sample file includes this data and example entries. The file must have the 399 | following information in the following order (**all entries required**): 400 | 401 | 1. name of machine hosting mySQL (usually localhost) 402 | 2. name of authorized user 403 | 3. password for above user 404 | 4. name of NextCloud database 405 | 406 | For example: 407 | 408 | ```Ini 409 | localhost 410 | nextcloud 411 | pAsSwOrD 412 | nextcloudDB 413 | ``` 414 | 415 | ### Protect your sql details file 416 | 417 | This file contains information on how to access your SQL installation therefore, 418 | you **must** protect it. You should lock it out for all users except root. 419 | Putting it in your root folder is not enough! Run the following commands to 420 | restrict access to the root user only (assuming filename is *'nc_sql.details'*): 421 | 422 | ```Bash 423 | chown root:root nc_sql.details # make root the owner 424 | chmod 600 nc_sql.details # restrict access to root only (read/write) 425 | ``` 426 | 427 | ## 503 functionality 428 | 429 | This script includes an entire section dedicated to copying an html file to act 430 | as an error 503 notification page. Error 503 is by definition "service 431 | temporarily unavailable" which is exactly the case for your NextCloud server 432 | during a backup since it is in maintenance mode and no logins are permitted. 433 | 434 | The script copies whatever file is defined by the *'-5'* parameter (or the 435 | default located at *'scriptpath/503.html'*) to whatever path is defined as the 436 | 'webroot' by the *'-w'* parameter. This means that if you omit the *'-w'* 437 | parameter, the script will necessarily skip this entire process and just issue a 438 | warning to let you know about it. 439 | 440 | ### Conditional forwarding by your webserver 441 | 442 | The script copying the file to the webroot is the easy part. Your webserver has 443 | to look for the presence of that file and generate a 503 error in order for the 444 | magic to happen. To do that, you have to include an instruction to that effect 445 | in your default server definition and/or your NextCloud virtual server 446 | definition file depending on your setup. 447 | 448 | #### NGINX 449 | 450 | You can copy the following code into the relevant server definition(s) on an 451 | NGINX server: 452 | 453 | ```Perl 454 | server { 455 | ... 456 | if (-f /usr/share/nginx/html/503.html) { 457 | return 503; 458 | } 459 | ... 460 | error_page 503 @backup 461 | location @backup { 462 | root /usr/share/nginx/html; 463 | rewrite ^(.*)$ /503.html break; 464 | } 465 | } 466 | ``` 467 | 468 | This tells NGINX that if it finds the file *'503.html'* at the path 469 | *'/usr/share/nginx/html'* (webroot) then return an error code 503. When it 470 | encounters an error 503, rewrite any url to *'domain.tld/503.html'* and thus, 471 | display the custom 503 error page. On the other hand, if it can't find 503.html 472 | at the path specified (i.e. the script has deleted it because the backup is 473 | completed), then go about business as usual. 474 | 475 | #### Apache 476 | 477 | I don't use apache for anything, ever... so I'm not sure how exactly you'd do 478 | this but I think you'd have to use something like: 479 | 480 | ```Perl 481 | RewriteEngine On 482 | RewriteCond %{ENV:REDIRECT_STATUS} !=503 483 | RewriteCond "/var/www/503.html" -f 484 | RewriteRule ^ - [R=503,L] 485 | ... 486 | ErrorDocument 503 /503.html 487 | ... 488 | ``` 489 | 490 | Let me know if that works and I'll update this document accordingly. Like I 491 | said, I don't use Apache so I can't really test it very easily. 492 | 493 | #### Disabling 503 functionality altogether 494 | 495 | If you don't want to use the 503 functionality for whatever reason and don't 496 | want your log file junked up with warnings about it, then find the section of 497 | the script file that starts with *'--- Begin 503 section ---'* and either 498 | comment all the lines (put a *'#'* at the beginning of each line) or delete all 499 | the lines until you get to *'--- End 503 section ---'*. 500 | 501 | ## Scheduling: Cron 502 | 503 | After running this script at least once manually to test your settings, you 504 | should schedule it to run automatically so things stay backed up. This is 505 | easiest with a simple cron job. 506 | 507 | 1. Open root's crontab: 508 | 509 | ```Bash 510 | sudo crontab -e 511 | ``` 512 | 513 | 2. Add your script command line and set the time. I'm assuming your script is 514 | located at *'/root/NCscripts'*, all files are at their default locations and 515 | you want to run your backup at 1:07am daily. 516 | 517 | ```Bash 518 | 7 1 * * * /root/NCscripts/backup.sh -d /var/nc_data -n /usr/share/nginx/html/nextcloud -u www-data -l /var/log/backup.log -w /usr/share/nginx/html > /dev/null 2>&1 519 | ``` 520 | 521 | The last part redirects all output to 'null' and forwards any errors to 522 | 'null' also. You don't need output because the script creates a wonderfully 523 | detailed log file that you can review :-) 524 | 3. Save the file and exit. 525 | 4. Confirm by listing the root user's crontab: 526 | 527 | ```Bash 528 | sudo crontab -l 529 | ``` 530 | 531 | ## The log file 532 | 533 | The script creates a very detailed log file of all major operations along with 534 | any errors and warnings. Everything is timestamped so you can see how long 535 | things take and when any errors took place. The script includes debugging 536 | notes such as where temp files are located, where it's looking for data, whether 537 | it created/moved/copied files, etc. All major operations are tagged *'-- [INFO] 538 | message here --'*. Similarily, warnings are tagged *'-- [WARNING] message here 539 | (code: xxxx) --'* and errors are tagged *'-- [ERROR] message here (code: xxx) 540 | --'*. Successful operations generate a *'-- [SUCCESS] message here --'* stamp. 541 | 542 | Sections of the script are all colour-coded to make viewing it easier. This 543 | means you should use something like *'cat backup.log | more'* or *'tail -n 544 | numberOfLines backup.log'* to view the file since the ansi colour codes 545 | would make it difficult to read in nano or vi. 546 | 547 | This tagging makes it easy for you to set up a log screening program to make 548 | keeping an eye on your backup results easier. If you plan on using Logwatch 549 | (highly recommended, great program!) then I've done the work for you... 550 | 551 | ### Using Logwatch 552 | 553 | Log-group, conf and service files are included so that you can easily setup 554 | Logwatch to monitor the script's log file and report at your desired detail 555 | level as follows: 556 | 557 | 1. 0: Summary of total success, warnings & errors only 558 | 2. 1-4: Actual success, error & warning messages 559 | 3. 5: Same as above, but includes info messages 560 | 4. 6+: Dumps entire raw log file including debugging messages 561 | 562 | A detailed breakdown of the files and all options are included in a separate 563 | readme in the *'/etc/logwatch'* folder of this git archive. 564 | 565 | If you don't really care how it works, then you can just copy the 566 | */etc/logwatch* folder to the appropriate Logwatch configuration directory for 567 | your system. The file directory layout in this git archive is already correct 568 | for Debian/Ubuntu systems. You will have to update the log-group file to 569 | reflect the path to your script's log file. 570 | ### Remember to rotate your logs 571 | 572 | The log file generated by this script is fairly detailed so it can grow quite 573 | large over time. This is especially true if you are using verbose output from 574 | borg for any troubleshooting or for compliance/auditing. I've included a sample 575 | commented logrotate config file in this git archive at *'/etc/logrotate.d'* 576 | which you can modify and drop into that same directory on your Debian/Ubuntu 577 | system. If you are using another log rotating solution, then please remember to 578 | configure it so that your log files don't get overwhelmingly large should you 579 | need to parse them if something goes wrong with your backups. 580 | 581 | ## Final notes 582 | 583 | I think that's everything. If I've forgotten to document something, please let 584 | me know. I know this readme is long but, I hate how much stuff for linux and 585 | open-source programs/scripts in general are so poorly documented especially for 586 | newbies and I didn't want to make that same mistake. 587 | 588 | I don't script too often and I'm a horrible programmer, so if you see anything 589 | that can be/should be improved, please let me know or submit your changes! I 590 | love learning new ways of doing things and getting feedback, so suggestions and 591 | comments are more than welcome. 592 | 593 | If this has helped you out, then please visit my blog at 594 | [https://mytechiethoughts.com](https://mytechiethoughts.com) where I solve 595 | problems like this all the time on a shoe-string or zero budget. Thanks! 596 | -------------------------------------------------------------------------------- /etc/logrotate.d/backup: -------------------------------------------------------------------------------- 1 | ### Rotate backup log file 2 | 3 | # location of log file (-l parameter of script file) 4 | /path/to/backup.log { 5 | 6 | # rotate log file weekly -- you could also use 'daily', 'monthly' or 7 | # specify a size using 'size 100k', for example 8 | weekly 9 | 10 | # keep 4 weeks of old logs (4 files) and delete older ones 11 | rotate 4 12 | 13 | # compress old log files using gzip (default) 14 | compress 15 | } 16 | -------------------------------------------------------------------------------- /etc/logwatch/conf/logfiles/backup.conf: -------------------------------------------------------------------------------- 1 | # Location of your script's log file, -l parameter 2 | LogFile = /path/to/your/backup.log 3 | 4 | # Format of logrotate archives for your script. Example assumes compression and 5 | # extension preservation 6 | Archive = /path/to/your/logfile.ext.?.gz 7 | 8 | # Apply the correct date/time filtering to match the format of the script's log 9 | # We are using a custom pl script in /etc/logwatch/scripts/shared/ 10 | # You don't need to change this unless you have altered the 'stamp' variable in 11 | # the script in which case you will want to update the regex in the custom pl 12 | # script below 13 | *sqFullStampAnywhere -------------------------------------------------------------------------------- /etc/logwatch/conf/services/backup.conf: -------------------------------------------------------------------------------- 1 | # Name of the logfile group without any extension 2 | LogFile = backup 3 | 4 | # Heading displayed on Logwatch's report for this service 5 | Title = "System and NextCloud Backup" 6 | 7 | # Override the detail level for this service 8 | # Remember the levels are: 0, 1-4, 5, 6+ 9 | # Detail = 0 -------------------------------------------------------------------------------- /etc/logwatch/readme.md: -------------------------------------------------------------------------------- 1 | # Using Logwatch to monitor backup script 2 | 3 | The backup script's log file has been set up so that utilities like Logwatch can 4 | easily parse it. In order to make that happen, a LogFile Group file, Service 5 | and Script have to be created for Logwatch to generate reports. The correct 6 | (general) directory structure has been created in this git archive already. 7 | Below are the details of each file. 8 | 9 | ## Contents 10 | 11 | - [LogFile Group file (/etc/logwatch/conf/logfiles/backup.conf)](#logfile-group-file-etclogwatchconflogfilesbackupconf) 12 | - [Log file location](#log-file-location) 13 | - [Archive location and name format](#archive-location-and-name-format) 14 | - [External script for timestamp processing](#external-script-for-timestamp-processing) 15 | - [Service definition file (/etc/logwatch/conf/services/backup.conf)](#service-definition-file-etclogwatchconfservicesbackupconf) 16 | - [LogFile Group file definition](#logfile-group-file-definition) 17 | - [Report title](#report-title) 18 | - [Detail level](#detail-level) 19 | - [Service script (/etc/logwatch/scripts/services/backup)](#service-script-etclogwatchscriptsservicesbackup) 20 | - [Detail levels](#detail-levels) 21 | - [Timestamp processing script (/etc/logwatch/scripts/shared/sqfullstampanywhere)](#timestamp-processing-script-etclogwatchscriptssharedsqfullstampanywhere) 22 | - [The time format specification](#the-time-format-specification) 23 | - [The search REGEX](#the-search-regex) 24 | - [Testing](#testing) 25 | - [Final thoughts](#final-thoughts) 26 | 27 | ## LogFile Group file (/etc/logwatch/conf/logfiles/backup.conf) 28 | 29 | ### Log file location 30 | 31 | Update this as needed to point to the location and name of the log file 32 | generated by the backup script. Remember, by default, the log file is created 33 | in the same directory as the script itself. 34 | 35 | ```Ini 36 | LogFile = /path/to/your/backup.log 37 | ... 38 | ``` 39 | 40 | Best practices suggest you use the *-l* 41 | flag to change this location to something like */var/log/backup.log*, for 42 | example. In that case, the entry would look like: 43 | 44 | ```Ini 45 | LogFile = /var/log/backup.log 46 | ... 47 | ``` 48 | 49 | ### Archive location and name format 50 | 51 | If you want Logwatch to process old (archived) log files generated by something 52 | like *Logrotate*, then you have to specify the location and file name format of 53 | those files. I've included the generalized compressed format of such rotated 54 | files as the default in the script. Suppose you store your log files in the 55 | recommended location (*/var/log/*) and are using *Logrotate* with compression 56 | enabled, the archive line would look like: 57 | 58 | ```Ini 59 | ... 60 | Archive = /var/log/backup.log.?.gz 61 | ... 62 | ``` 63 | 64 | This would tell Logwatch, when the archive option is set to true, that your 65 | *backup.log* files are archived as: *backup.log.1.gz*, *backup.log.2.gz*, etc. 66 | and are all located in */var/log/*. 67 | 68 | **Note: This line is totally optional and only used if you set the archive 69 | option in Logwatch to true (default). You can comment/delete this line if you 70 | wish.** 71 | 72 | ### External script for timestamp processing 73 | 74 | Since the log file uses a non-standard (according to Logwatch) method of 75 | datestamping, a custom filter had to be created. See the 76 | [relevant](#timestamp-processing-script-etclogwatchscriptssharedsqfullstampanywhere) 77 | section of this document for more information. 78 | 79 | The script file is called with an *\** before the filename. 80 | 81 | ```Ini 82 | ... 83 | *sqFullStampAnywhere 84 | ... 85 | ``` 86 | 87 | If you change the name of this file, you will have to change this line. 88 | Remember that whatever you type here as a name is converted to all-lowercase 89 | so your filename should be all lowercase also. 90 | 91 | ## Service definition file (/etc/logwatch/conf/services/backup.conf) 92 | 93 | ### LogFile Group file definition 94 | 95 | The service file needs to know what group of log files it is responsible for 96 | processing. This MUST match the name of your *LogFile Group file*: 97 | 98 | ```Ini 99 | LogFile = backup 100 | ... 101 | ``` 102 | 103 | If you change your LogFile Group filename, then update it here too without the 104 | *.conf* extension. 105 | 106 | ### Report title 107 | 108 | The Logwatch output file (html or text) is divided into sections. You can 109 | define the title to be anything that has meaning for you. I have arbitrarily 110 | chosen *"System and NextCloud Backup"* but you can change it to anything you want by 111 | modifying the line: 112 | 113 | ```Ini 114 | ... 115 | Title = "System and NextCloud Backup" 116 | ``` 117 | 118 | ### Detail level 119 | 120 | If you want to set the *detail* level of this service differently from your 121 | other services (which will use the *--detail* switch value or the value in your 122 | *logwatch.conf*), then you can define that level here. By default, it appears 123 | like this in the service configuration file: 124 | 125 | ```Ini 126 | ... 127 | # Override the detail level for this service 128 | # Remember the levels are: 0, 1-4, 5, 6+ 129 | # Detail = 0 130 | ``` 131 | 132 | Simply change it to the value you want enforced. For example, here I'm setting 133 | it to output level 5 regardless of whatever settings everything else is using. 134 | 135 | ```Ini 136 | # Override the detail level for this service 137 | # Remember the levels are: 0, 1-4, 5, 6+ 138 | Detail = 5 139 | ``` 140 | 141 | ## Service script (/etc/logwatch/scripts/services/backup) 142 | 143 | Logwatch calls any script with a name that **matches the service name**. You'll 144 | notice that I just named everything *backup* to keep things simple. You can 145 | change this to whatever you want, however. If you changed the service name to 146 | *"NCbackup*.conf", for example, you would have to rename this script file to 147 | "*NCbackup*" with no extension. Note: The script is a PERL file (note the 148 | shebang) but it can be written in any language. 149 | 150 | In essence, Logwatch just spits out the log file(s) defined in the LogFile Group 151 | file as standard input (STDIN) for the script and then takes whatever is output 152 | (STDOUT) from the script to assemble into it's report. 153 | 154 | ### Detail levels 155 | 156 | The script supports four (4) detail levels as follows: 157 | 158 | - **Level 0: Summary output only** 159 | - This will display an aggregate total of certain logged elements. It will 160 | display the total number successful script executions (SQL dump OK, borg 161 | backup OK and borg prune OK), total generated warnings and total errors 162 | encountered that stopped the normal execution of the script. All totals are 163 | relative to the reporting period Logwatch is using (--range parameter). 164 | 165 | **This is the recommended reporting level.** It does not take up much space 166 | and is quick to read. If you notice warnings and/or errors, you should 167 | consult the full logs. 168 | - **Levels 1-4: Critical messages** 169 | - This uses the data which is summarized by Level 0 but outputs the actual 170 | messages in the log file. For example, you will see the actual text of the 171 | errors logged instead of just a total number of errors. This level of 172 | reporting is useful when *initially* monitoring the script's operation since 173 | you can see the actual text of any generated warnings/errors. 174 | - **Level 5: Verbose (debugging) output** 175 | - Like the previous level, this outputs the actual messages found in the log 176 | file. However, it also includes *[INFO] tags* which contain logged 177 | operational messages such as created temporary directories, entering/exiting 178 | maintenance mode, what source files are being used to determine extra file 179 | inclusions/exclusions, etc. This level of reporting is useful in diagnosing 180 | why errors are occurring or if you just want more insight into how the 181 | script works. 182 | 183 | **This level of output will make your Logwatch reports longer and consume 184 | more of your time to review. You should not use this level day-to-day.** 185 | - **Levels 6+: Complete log file dump** 186 | - Any number greater than 5 passed as a detail level will trigger the script 187 | to dump the entire log file out to Logwatch line-by-line. This is useful 188 | only if you are debugging an issue and cannot get access to the actual raw 189 | log file itself. The actual log file is colour-coded which makes it much 190 | easier to read for debugging purposes. 191 | 192 | **Use this detail level only when you need to see the entire log file and 193 | cannot otherwise access the log file.** 194 | 195 | ## Timestamp processing script (/etc/logwatch/scripts/shared/sqfullstampanywhere) 196 | 197 | This is basically a modified version of the '*applyeurodate*' script that comes 198 | with Logwatch. It had to be modified to search within [square brackets] and to 199 | accept characters coming before the stamp (i.e. ANSI colour codes). If you 200 | change the '**stamp**' variable in the backup script to update the timestamp to 201 | your liking (which to totally fine!) then you'll probably have to update this 202 | file. There are two lines you need to modify to suit your new '**stamp**' 203 | variable. 204 | 205 | ### The time format specification 206 | 207 | '*$SearchDate*' is the variable used in the PERL script to do exactly what it 208 | says, search for the date stamp. I have it set up to look for the format 209 | '*year-month-date hour:minute:second*'. Note, we don't care about brackets or 210 | anything here, we're just defining the format of the date/time stamp. 211 | 212 | ```Perl 213 | ... 214 | $SearchDate = TimeFilter('%Y-%m-%d %H:%M:%S'); 215 | ... 216 | ``` 217 | 218 | If you changed the '**stamp**' variable so it was formatted as '*month/day/year 219 | hour:minute*' (ex: '*[09/27/2018 18:38]*') then you'd update the **$SearchDate** 220 | variable as follows (note: no mention of the square brackets!): 221 | 222 | ```Perl 223 | ... 224 | $SearchDate = TimeFilter('%m/%d/%Y %H:%M'); 225 | ... 226 | ``` 227 | 228 | ### The search REGEX 229 | 230 | The PERL script uses a '*regular expression*' (REGEX) to search within the log file for 231 | '*$SearchDate*'. For the default datestamp, this specification looks like: 232 | 233 | ```Perl 234 | ... 235 | if ($ThisLine =~ m/\[$SearchDate\] /o) { 236 | ... 237 | ``` 238 | 239 | The REGEX appears between '*m/*' and '*/o*'. In this case, it searches for 240 | '*$SearchDate*' inside [square brackets] appearing anywhere on the line. This 241 | is because ANSI colour-codes often appear before the datestamp in the default 242 | log file. If you have modified this so that your datestamp appears at the 243 | beginning of the line and in the example format in the section above (using 244 | slashes instead of dashes) then you'd rewrite this REGEX as follows: 245 | 246 | ```Perl 247 | ... 248 | if ($ThisLine =~ m/^\[$SearchDate\] /o) { 249 | ... 250 | ``` 251 | 252 | or using regular brackets anywhere on the line: 253 | 254 | ```Perl 255 | ... 256 | if ($ThisLine =~ m/\($SearchDate\) /o) { 257 | ... 258 | ``` 259 | 260 | or without any brackets but appearing at the beginning of the line: 261 | 262 | ```Perl 263 | ... 264 | if ($ThisLine =~ m/^$SearchDate /o) { 265 | ... 266 | ``` 267 | 268 | ## Testing 269 | 270 | Run *logwatch --help* and note the options. You can test just this service 271 | locally on your screen with the following command (assuming you kept default 272 | names for everything): 273 | 274 | ```Bash 275 | # Summary output, entire duration of log file 276 | logwatch --service backup --output stdout --format text --range all --detail 0 277 | 278 | # Minimal detail, yesterday only 279 | logwatch --service backup --output stdout --format text --range yesterday --detail 3 280 | 281 | # Verbose output, today only 282 | logwatch --service backup --output stdout --format text --range today --detail 5 283 | ``` 284 | 285 | ## Final thoughts 286 | 287 | That's it! I'm a horrible PERL programmer so if anyone can optimize/improve the 288 | script file used for Logwatch then please do it! Otherwise, I hope this made 289 | sense and helped you integrate the backup script with Logwatch for easy 290 | monitoring :-) -------------------------------------------------------------------------------- /etc/logwatch/scripts/services/backup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | ############################################################################# 4 | # $Id$ 5 | ############################################################################# 6 | # Log: Backup script (backup) 7 | # Revision 1.0 2018/10/16 8 | # Written by Asif Bacchus 9 | ############################################################################# 10 | 11 | 12 | use strict; 13 | 14 | ### Get Logwatch detail level (default to 0) 15 | my $detailLevel = $ENV{'LOGWATCH_DETAIL_LEVEL'} || 0; 16 | 17 | 18 | ### Declare variables 19 | my $summaryErr; 20 | my $summaryWarn; 21 | my $summarySuccess; 22 | 23 | my %reportHash = (); 24 | my $key; 25 | 26 | 27 | ### Minimal detail level: provide summary data only 28 | if ($detailLevel == 0) { 29 | ### process logfile and summarize message types 30 | while (defined(my $ThisLine = )) { 31 | if ($ThisLine =~ /\-- \[ERROR\] /) { 32 | $summaryErr++; 33 | } 34 | elsif ($ThisLine =~ /\-- \[WARNING\] /) { 35 | $summaryWarn++; 36 | } 37 | elsif ($ThisLine =~ /All processes completed successfully/) { 38 | $summarySuccess++; 39 | } 40 | } 41 | 42 | ### fill hash table with headings and summary counts 43 | if ($summarySuccess > 0) { 44 | $reportHash{"All processes successfully completed"} = $summarySuccess; 45 | } 46 | if ($summaryWarn > 0) { 47 | $reportHash{"Warnings issued"} = $summaryWarn; 48 | } 49 | if ($summaryErr > 0) { 50 | $reportHash{"Errors encountered"} = $summaryErr; 51 | } 52 | 53 | ### print hash table 54 | foreach $key (sort keys %reportHash) { 55 | print "$key: $reportHash{$key}\n"; 56 | } 57 | } 58 | ### Levels 1-4 provide the actual error, warning and success messages instead 59 | ### of a summary count 60 | elsif ($detailLevel >= 1 && $detailLevel <= 4) { 61 | while (defined(my $ThisLine = )) { 62 | if ($ThisLine =~ /\-- \[ERROR\] /) { 63 | print $ThisLine; 64 | } 65 | elsif ($ThisLine =~ /\-- \[WARNING\] /) { 66 | print $ThisLine; 67 | } 68 | elsif ($ThisLine =~ /\-- \[SUCCESS\] /) { 69 | print $ThisLine; 70 | } 71 | } 72 | } 73 | ### Level 5 is similiar to levels 1-4 except it also reports informational 74 | ### messages such as the location of script created files, variable checks, 75 | ### etc. This is useful when verifying the script's operation. 76 | elsif ($detailLevel == 5) { 77 | while (defined(my $ThisLine = )) { 78 | if ($ThisLine =~ /\-- \[ERROR\] /) { 79 | print $ThisLine; 80 | } 81 | elsif ($ThisLine =~ /\-- \[WARNING\] /) { 82 | print $ThisLine; 83 | } 84 | elsif ($ThisLine =~ /\-- \[SUCCESS\] /) { 85 | print $ThisLine; 86 | } 87 | elsif ($ThisLine =~ /\-- \[INFO\] /) { 88 | print $ThisLine; 89 | } 90 | } 91 | } 92 | ### Any level above 5 will echo the entire log including the debugging notes 93 | ### within the script meant for troubleshooting. Using this level of detail 94 | ### should only be done if you cannot view the actual log file directly for 95 | ### whatever reason. The actual log file is colour-coded for easier debugging. 96 | elsif ($detailLevel > 5) { 97 | while (defined(my $ThisLine = )) { 98 | print $ThisLine; 99 | } 100 | } 101 | 102 | 103 | 104 | ### Exit gracefully 105 | exit (0); 106 | 107 | # vi: shiftwidth=3 tabstop=3 et 108 | # Local Variables: 109 | # mode: perl 110 | # perl-indent-level: 3 111 | # indent-tabs-mode: nil 112 | # End: -------------------------------------------------------------------------------- /etc/logwatch/scripts/shared/sqfullstampanywhere: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | ########################################################################## 4 | # $Id$ 5 | ########################################################################## 6 | 7 | ############################################################################### 8 | ## Filter dates in full-date-time international format, surrounded by square 9 | ## brackets located anywhere on a given line 10 | ## Format: '[%Y-%m-%d %H:%M:%S]' 11 | ############################################################################### 12 | 13 | use Logwatch ':dates'; 14 | 15 | my $Debug = $ENV{'LOGWATCH_DEBUG'} || 0; 16 | 17 | ### Specify the format of the date/time stamp itself 18 | $SearchDate = TimeFilter('%Y-%m-%d %H:%M:%S'); 19 | 20 | if ( $Debug > 5 ) { 21 | print STDERR "DEBUG: Inside FullDateTime...\n"; 22 | print STDERR "DEBUG: Looking For: " . $SearchDate . "\n"; 23 | } 24 | 25 | while (defined($ThisLine = )) { 26 | ### specify the regex that defines how to find 'SearchDate' 27 | if ($ThisLine =~ m/\[$SearchDate\] /o) { 28 | print $ThisLine; 29 | } 30 | } 31 | 32 | # vi: shiftwidth=3 syntax=perl tabstop=3 et 33 | # Local Variables: 34 | # mode: perl 35 | # perl-indent-level: 3 36 | # indent-tabs-mode: nil 37 | # End: 38 | -------------------------------------------------------------------------------- /root/NCscripts/503.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 503 - Unavailable: Backup in progress 7 | 8 | 9 | 17 | 18 | 19 | 20 |

Bad timing!

21 |

Seems you're trying to access me during my daily backup window. Don't 22 | worry though, I should be up and running again very soon.

23 |

My average backup window duration is around 10 minutes during which time 24 | I'm quite busy copying your super-important files to my ultra-secret hiding 25 | place so they stay safe in case anything ever happens to me!

26 |

I'm really sorry for the delay. Please try me again soon!

27 | 28 | 29 | -------------------------------------------------------------------------------- /root/NCscripts/backup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | 4 | ### Text formatting presets 5 | normal="\e[0m" 6 | bold="\e[1m" 7 | default="\e[39m" 8 | err="\e[1;31m" 9 | warn="\e[1;93m" 10 | ok="\e[32m" 11 | lit="\e[93m" 12 | op="\e[39m" 13 | info="\e[96m" 14 | note="\e[95m" 15 | 16 | 17 | ### Functions ### 18 | 19 | ### scriptHelp -- display usage information for this script 20 | function scriptHelp { 21 | echo -e "${bold}${note}\n${scriptName} usage instructions:\n${normal}" 22 | echo -e "${default}This script performs a backup of your NextCloud system" 23 | echo -e "assuming a fairly standard set up such as outlined at" 24 | echo -e "${lit}https://mytechiethoughts.com${default}. Full details about" 25 | echo -e "this script can be found at that site." 26 | echo -e "${bold}\nThe script performs the following tasks:${normal}${default}" 27 | echo -e "1. Puts NextCloud in maintenance mode." 28 | echo -e "2. Optionally copies a 503 error page to your webroot." 29 | echo -e "3. Dumps SQL to a temporary directory." 30 | echo -e "4. Invokes borgbackup to backup your SQL info, NextCloud program" 31 | echo -e "\tand data files along with any other files you specify." 32 | echo -e "5. Removes temp files, the 503 error page and restores" 33 | echo -e "\tNextCloud to operational status." 34 | echo -e "\nThe readme file included in this script's git contains detailed" 35 | echo -e "usage information. The following is a brief summary:\n" 36 | echo -e "${bold}${note}Mandatory parameters:${normal}${default}" 37 | echo -e "${lit}\n-d, NextCloud data directory${default}" 38 | echo -e "This is the physical location of your NextCloud data." 39 | echo -e "${lit}\n-n, NextCloud webroot${default}" 40 | echo -e "This is the location of the actual NextCloud web files (php & html" 41 | echo -e ",etc.), usually within your NGINX or Apache webroot." 42 | echo -e "${lit}\n-u, NGINX/Apache webuser account${default}" 43 | echo -e "The webuser account NGINX/Apache (and thus, NextCloud) are running" 44 | echo -e "under. Some actions must run as this user due to file ownership" 45 | echo -e "restrictions." 46 | echo -e "${bold}${note}\nOptional parameters:${normal}${default}" 47 | echo -e "${lit}\n-5, Location of 503 error page file${default}" 48 | echo -e "FULL PATH to the 503 error page HTML file you want copied to your" 49 | echo -e "webroot to inform users the server is down during the backup. If" 50 | echo -e "you don't specify a path/file, the default will be used. If the" 51 | echo -e "default cannot be found, a warning will be logged and the script" 52 | echo -e "will continue." 53 | echo -e "${info}Default: ScriptPath/503.html${default}" 54 | echo -e "${lit}\n-b, Location of file with borg repo details${default}" 55 | echo -e "FULL PATH to the plain text file containing all information needed" 56 | echo -e "to connect and process your borg repo. Details on the structure of" 57 | echo -e "this file are in the readme and on ${lit}https://mytechiethoughts.com${default}" 58 | echo -e "${info}Default: ScriptPath/nc_borg.details${default}" 59 | echo -e "${lit}\n-l, Location to save log file${default}" 60 | echo -e "This script writes a detailed log file of all activities. It is" 61 | echo -e "structured in an way easy for log parsers (like Logwatch) to read." 62 | echo -e "${info}Default: ScriptPath/ScriptName.log${default}" 63 | echo -e "${lit}\n-s, Location of file with mySQL details${default}" 64 | echo -e "FULL PATH to the plain text file containing all information needed" 65 | echo -e "to connect to your mySQL (mariaDB) server and NextCloud database." 66 | echo -e "Details on the structure of this file are in the readme and on ${lit}" 67 | echo -e "https://mytechiethoughts.com${default}" 68 | echo -e "${info}Default: ScriptPath/nc_sql.details${default}" 69 | echo -e "${lit}\n-v, Verbose output from borgbackup${default}" 70 | echo -e "By default, this script will only log summary data from borg." 71 | echo -e "If you need/want more detailed information, the verbose setting" 72 | echo -e "will list every file processed along with their status. Note: Your" 73 | echo -e "log file can quickly get very very large using this option!" 74 | echo -e "${info}Default: NOT activated (standard logging)${default}" 75 | echo -e "${lit}\n-w, webserver's webroot directory${default}" 76 | echo -e "This is the location from which your webserver (NGINX, Apache," 77 | echo -e "etc.) physically stores files to be served. This is NOT the" 78 | echo -e "configuration directory for your webserver! It is the place" 79 | echo -e "where the actual HTML/PHP/CSS/JS/etc. files are stored." 80 | echo -e "NOTE: If you omit this option, then the entire 503 copy process" 81 | echo -e "will be skipped regardless of the presence of a 503.html file." 82 | echo -e "If you don't want to use the 503 feature, omitting this is an easy" 83 | echo -e "way to skip it!" 84 | echo -e "${info}Default: NONE${default}" 85 | echo -e "${lit}\n-?, This help screen${default}\n" 86 | echo -e "${bold}Please refer to the readme file and/or ${lit}https://mytechiethoughts.com${default}" 87 | echo -e "for more information on this script.${normal}\n" 88 | # exit with code 1 -- there is no use logging this 89 | exit 1 90 | } 91 | 92 | ### generate dynamic timestamps 93 | function stamp { 94 | echo `date +%F" "%T` 95 | } 96 | 97 | ### quit -- exit the script after logging any errors, warnings, etc. 98 | function quit { 99 | # list generated warnings, if any 100 | if [ ${#exitWarn[@]} -gt 0 ]; then 101 | echo -e "${warn}${scriptName} generated the following warnings:" \ 102 | "${normal}" >> "$logFile" 103 | for warnCode in "${exitWarn[@]}"; do 104 | warnStamp="${warnCode%%_*}" 105 | warnValue="${warnCode##*_}" 106 | echo -e "${warn}${warnStamp} -- [WARNING]" \ 107 | "${warningExplain[$warnValue]} (code: ${warnValue}) --" \ 108 | "${normal}" >> "$logFile" 109 | done 110 | fi 111 | if [ -z "${exitError}" ]; then 112 | # exit cleanly 113 | echo -e "${note}[$(stamp)] --- ${scriptName} completed" \ 114 | "---${normal}" >> "$logFile" 115 | exit 0 116 | else 117 | # list generated errors and explanations then exit script with code 2 118 | echo -e "${err}${scriptName} generated the following errors:" \ 119 | "${normal}" >> "$logFile" 120 | for errCode in "${exitError[@]}"; do 121 | errStamp="${errCode%%_*}" 122 | errValue="${errCode##*_}" 123 | echo -e "${err}${errStamp} -- [ERROR] ${errorExplain[$errValue]}" \ 124 | "(code: ${errValue}) --${normal}" >> "$logFile" 125 | done 126 | exit 2 127 | fi 128 | } 129 | 130 | function checkExist { 131 | if [ "$1" = "ff" ]; then 132 | # find file 133 | if [ -f "$2" ]; then 134 | # found 135 | return 0 136 | else 137 | # not found 138 | return 1 139 | fi 140 | elif [ "$1" = "fd" ]; then 141 | # find directory 142 | if [ -d "$2" ]; then 143 | # found 144 | return 0 145 | else 146 | # not found 147 | return 1 148 | fi 149 | fi 150 | } 151 | 152 | ### ncMaint - pass requested mode change type to NextCloud occ 153 | function ncMaint { 154 | sudo -u "${webUser}" php "${ncRoot}/occ" maintenance:mode --"$1" \ 155 | >> "$logFile" 2>&1 156 | maintResult="$?" 157 | return "$maintResult" 158 | } 159 | 160 | ### cleanup - cleanup files and directories created by this script 161 | function cleanup { 162 | ## remove SQL dump file and directory 163 | rm -rf "$sqlDumpDir" >> "$logFile" 2>&1 164 | # verify directory is gone 165 | checkExist fd "$sqlDumpDir" 166 | checkResult="$?" 167 | if [ "$checkResult" = "0" ]; then 168 | # directory still exists 169 | exitWarn+=("[$(stamp)]_111") 170 | else 171 | # directory removed 172 | echo -e "${op}[$(stamp)] Removed SQL temp directory${normal}" \ 173 | >> "$logFile" 174 | fi 175 | 176 | ## remove 503 error page 177 | # check value of 'clean503' to see if this is necessary (=1) otherwise, skip 178 | if [ "$clean503" = "1" ]; then 179 | # proceed with cleanup 180 | echo -e "${op}[$(stamp)] Removing 503 error page..." >> "$logFile" 181 | rm -f "$webroot/$err503File" >> "$logFile" 2>&1 182 | # verify file is actually gone 183 | checkExist ff "$webroot/$err503File" 184 | checkResult="$?" 185 | if [ "$checkResult" = "0" ]; then 186 | # file still exists 187 | exitWarn+=("[$(stamp)]_5030") 188 | else 189 | # file removed 190 | echo -e "${info}[$(stamp)] -- [INFO] 503 page removed from webroot" \ 191 | "--${normal}" >> "$logFile" 192 | fi 193 | else 194 | echo -e "${op}[$(stamp)] 503 error page never copied to webroot," \ 195 | "nothing to cleanup" >> "$logFile" 196 | fi 197 | 198 | ## Exit NextCloud maintenance mode regardless of current status 199 | ncMaint off 200 | # check if successful 201 | if [ "$maintResult" = "0" ]; then 202 | echo -e "${info}[$(stamp)] -- [INFO] NextCloud now in regular" \ 203 | "operating mode --${normal}" >> "$logFile" 204 | else 205 | exitError+=("[$(stamp)]_101") 206 | quit 207 | fi 208 | } 209 | 210 | ### End of Functions ### 211 | 212 | 213 | ### Default parameters 214 | 215 | # store the logfile in the same directory as this script using the script's name 216 | # with the extension .log 217 | scriptPath="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 218 | scriptName="$( basename ${0} )" 219 | logFile="$scriptPath/${scriptName%.*}.log" 220 | 221 | # set default 503 error page name and location in scriptPath 222 | err503Path="$scriptPath/503.html" 223 | err503File="${err503Path##*/}" 224 | 225 | # set default sqlDetails path to scriptPath 226 | sqlDetails="$scriptPath/nc_sql.details" 227 | 228 | # set default borgDetails path to scriptPath 229 | borgDetails="$scriptPath/nc_borg.details" 230 | 231 | # set borg parameters to 'normal' verbosity 232 | borgCreateParams='--stats' 233 | borgPruneParams='--list' 234 | 235 | 236 | ### Set script parameters to null and initialize array variables 237 | unset PARAMS 238 | unset sqlDumpDir 239 | unset webroot 240 | unset ncRoot 241 | unset webUser 242 | unset clean503 243 | unset sqlParams 244 | unset ncDataDir 245 | unset borgXtra 246 | unset borgExclude 247 | unset borgPrune 248 | unset BORG_BASE_DIR 249 | unset BORG_RSH 250 | unset BORG_REPO 251 | unset BORG_PASSPHRASE 252 | unset BORG_REMOTE_PATH 253 | unset TMPDIR 254 | exitError=() 255 | errorExplain=() 256 | exitWarn=() 257 | warningExplain=() 258 | borgConfig=() 259 | xtraFiles=() 260 | 261 | ### Error codes 262 | errorExplain[100]="Could not put NextCloud into maintenance mode" 263 | errorExplain[101]="Could not exit NextCloud maintenance mode" 264 | errorExplain[200]="Could not dump NextCloud SQL database" 265 | errorExplain[210]="Invalid or non-existant borg base directory specified (borg backup details file)" 266 | errorExplain[211]="Invalid or non-existant path to borg SSH keyfile (borg backup details file)" 267 | errorExplain[212]="Name of borg repo was not specified (borg backup details file)" 268 | errorExplain[215]="Could not find/create 'tmp' directory within borg base directory. Please manually create it and ensure it's writable" 269 | errorExplain[220]="Borg exited with a critical error. Please check this script's logfile for details" 270 | errorExplain[221]="Borg prune exited with ERRORS. Please check this script's logfile for details" 271 | 272 | ### Warning codes & messages 273 | warningExplain[111]="Could not remove SQL dump file and directory, please remove manually" 274 | warningExplain[5030]="Could not remove 503 error page. This MUST be removed manually before NGINX will serve webclients!" 275 | warningExplain[5031]="No webroot path was specified (-w parameter missing)" 276 | warningExplain[5032]="The specified webroot (-w parameter) could not be found" 277 | warningExplain[5033]="No 503 error page could be found. If not using the default located in the script directory, then check your -5 parameter" 278 | warningExplain[5035]="Error copying 503 error page to webroot" 279 | warn503="Web users will NOT be informed the server is down!" 280 | warningExplain[2111]="No password used for access to remote borg repo. This is an insecure configuration" 281 | warningExplain[2112]="No remote borg instance specified. Operations will be slower in this configuration" 282 | warningExplain[2113]="The specified file containing extra files for inclusion in borgbackup could not be found" 283 | warningExplain[2114]="The specified file containing exclusion patterns for borgbackup could not be found. Backup was performed as though NO exclusions were defined" 284 | warningExplain[2115]="No paramters provided for borg prune. No repo pruning has taken place. You should reconsider this decision to control the size/history of your backups" 285 | warningExplain[2116]="No additional locations are specified for inclusion in backup. ONLY NextCloud DATA will be backed up (no configuration, etc). If this is unintentional, check the inclusion file referenced in your borgbackup settings" 286 | warningExplain[2200]="Borg completed with warnings. Please check this script's logfile for details" 287 | warningExplain[2201]="Borg exited with an unknown return-code. Please check this script's logfile for details" 288 | warningExplain[2210]="Borg prune exited with warnings. Please check this script's logfile for details" 289 | warningExplain[2212]="Borg prune exited with an unknown return-code. Please check this script's logfile for details" 290 | 291 | 292 | ### Process script parameters 293 | 294 | # If parameters are provided but don't start with '-' then show the help page 295 | # and exit with an error 296 | if [ -n "$1" ] && [[ ! "$1" =~ ^- ]]; then 297 | # show script help page 298 | scriptHelp 299 | fi 300 | 301 | # use GetOpts to process parameters 302 | while getopts ':l:n:u:v5:w:s:b:d:' PARAMS; do 303 | case "$PARAMS" in 304 | l) 305 | # use provided location for logFile 306 | logFile="${OPTARG%/}" 307 | ;; 308 | n) 309 | # NextCloud webroot 310 | ncRoot="${OPTARG%/}" 311 | ;; 312 | u) 313 | # webuser 314 | webUser="${OPTARG}" 315 | ;; 316 | v) 317 | # verbose output from Borg 318 | borgCreateParams='--list --stats' 319 | borgPruneParams='--list' 320 | ;; 321 | 5) 322 | # Full path to 503 error page 323 | err503Path="${OPTARG%/}" 324 | err503File="${err503Path##*/}" 325 | ;; 326 | w) 327 | # path to webserver webroot to copy 503 error page 328 | webroot="${OPTARG%/}" 329 | ;; 330 | s) 331 | # path to file containing SQL login details 332 | sqlDetails="${OPTARG%/}" 333 | ;; 334 | b) 335 | # path to file containing borgbackup settings and details 336 | borgDetails="${OPTARG%/}" 337 | ;; 338 | d) 339 | # nextcloud data directory 340 | ncDataDir="${OPTARG%/}" 341 | ;; 342 | ?) 343 | # unrecognized parameters trigger scriptHelp 344 | scriptHelp 345 | ;; 346 | esac 347 | done 348 | 349 | 350 | ### Verify script pre-requisties 351 | 352 | ## If not running as root, display error on console and exit 353 | if [ $(id -u) -ne 0 ]; then 354 | echo -e "\n${err}This script MUST be run as ROOT. Exiting.${normal}" 355 | exit 3 356 | fi 357 | 358 | ## Check NextCloud webroot 359 | # Ensure NextCloud webroot is provided 360 | if [ -z "$ncRoot" ]; then 361 | echo -e "\n${err}The NextCloud webroot must be specified (-n parameter)" \ 362 | "${normal}\n" 363 | exit 1 364 | # Ensure NextCloud webroot directory exists 365 | elif [ -n "$ncRoot" ]; then 366 | checkExist fd "$ncRoot" 367 | checkResult="$?" 368 | if [ "$checkResult" = "1" ]; then 369 | # Specified NextCloud webroot directory could not be found 370 | echo -e "\n${err}The provided NextCloud webroot directory" \ 371 | "(-n parameter) does not exist.${normal}\n" 372 | exit 1 373 | fi 374 | fi 375 | 376 | ## Check NextCloud webuser account 377 | # Ensure NextCloud webuser account is provided 378 | if [ -z "$webUser" ]; then 379 | echo -e "\n${err}The webuser account running NextCloud must be provided" \ 380 | "(-u parameter)${normal}\n" 381 | exit 1 382 | # Check if supplied webUser account exists 383 | elif [ -n "$webUser" ]; then 384 | user_exists=$(id -u "$webUser" > /dev/null 2>&1; echo $?) 385 | if [ "$user_exists" -ne 0 ]; then 386 | echo -e "\n${err}The supplied webuser account (-u parameter) does not" \ 387 | "exist.${normal}\n" 388 | exit 1 389 | fi 390 | fi 391 | 392 | ## Ensure sqlDetails file exists 393 | checkExist ff "$sqlDetails" 394 | checkResult="$?" 395 | if [ "$checkResult" = "1" ]; then 396 | # sqlDetails file cannot be found 397 | echo -e "\n${err}The file containing your SQL details does not exist" \ 398 | "(-s parameter)${normal}\n" 399 | exit 1 400 | fi 401 | 402 | ## Ensure borgDetails file exists 403 | checkExist ff "$borgDetails" 404 | checkResult="$?" 405 | if [ "$checkResult" = "1" ]; then 406 | # sqlDetails file cannot be found 407 | echo -e "\n${err}The file containing your borgbackup details does not" \ 408 | "exist (-b parameter)${normal}\n" 409 | exit 1 410 | fi 411 | 412 | ## Check NextCloud data directory 413 | # Ensure NextCloud data directory is provided 414 | if [ -z "$ncDataDir" ]; then 415 | echo -e "\n${err}The NextCloud data directory must be specified" \ 416 | "(-d parameter)${normal}\n" 417 | exit 1 418 | # Ensure NextCloud data directory exists 419 | elif [ -n "$ncDataDir" ]; then 420 | checkExist fd "$ncDataDir" 421 | checkResult="$?" 422 | if [ "$checkResult" = "1" ]; then 423 | # Specified NextCloud data directory could not be found 424 | echo -e "\n${err}The provided NextCloud data directory" \ 425 | "(-d parameter) does not exist.${normal}\n" 426 | exit 1 427 | fi 428 | fi 429 | 430 | 431 | ### Log start of script operations 432 | echo -e "${note}[$(stamp)] --- Start $scriptName execution ---${normal}" \ 433 | >> "$logFile" 434 | echo -e "${info}[$(stamp)] -- [INFO] Log file located at ${lit}${logFile}${info}" \ 435 | "--${normal}" >> "$logFile" 436 | 437 | 438 | ### Export logFile variable for use by Borg 439 | export logFile="$logFile" 440 | 441 | 442 | ### Create sqlDump temporary directory and sqlDumpFile name 443 | sqlDumpDir=$( mktemp -d ) 444 | sqlDumpFile="backup-`date +%Y%m%d_%H%M%S`.sql" 445 | echo -e "${info}[$(stamp)] -- [INFO] mySQL dump file will be stored" \ 446 | "at: ${lit}${sqlDumpDir}/${sqlDumpFile}${normal}" >> "$logFile" 447 | 448 | 449 | ### 503 error page: If you don't plan on using the auto-copied 503 then comment 450 | ### this entire section starting with '--- Begin 503 section ---' until 451 | ### '--- End 503 section ---' to suppress generated warnings 452 | 453 | ### --- Begin 503 section --- 454 | 455 | ## Check if webroot has been specified, if not, skip this entire section since there is nowhere to copy the 503 file. 456 | if [ -z "$webroot" ]; then 457 | # no webroot path provided 458 | echo -e "${info}[$(stamp)] -- [INFO] ${warn503} --${normal}" \ 459 | >> "$logFile" 460 | exitWarn+=("[$(stamp)]_5031") 461 | clean503=0 462 | else 463 | # verify webroot actually exists 464 | checkExist fd "$webroot" 465 | checkResult="$?" 466 | if [ "$checkResult" = "1" ]; then 467 | # webroot directory specified could not be found 468 | echo -e "${info}[$(stamp)] -- [INFO] ${warn503} --${normal}" \ 469 | >> "$logFile" 470 | exitWarn+=("{$stamp}_5032") 471 | clean503=0 472 | else 473 | # webroot exists 474 | echo -e "${op}[$(stamp)] Using webroot: ${lit}${webroot}${normal}" \ 475 | >> "$logFile" 476 | # Verify 503 file existance at given path 477 | checkExist ff "$err503Path" 478 | checkResult="$?" 479 | if [ "$checkResult" = "1" ]; then 480 | # 503 file could not be found 481 | echo -e "${info}[$(stamp)] -- [INFO] ${warn503} --${normal}" \ 482 | >> "$logFile" 483 | exitWarn+=("[$(stamp)]_5033") 484 | clean503=0 485 | else 486 | # 503 file exists and webroot is valid. Let's copy it! 487 | echo -e "${op}[$(stamp)] ${err503File} found at ${lit}${err503Path}" \ 488 | "${normal}" >> "$logFile" 489 | echo -e "${op}[$(stamp)] Copying 503 error page to webroot..." \ 490 | "${normal}" >> "$logFile" 491 | cp "${err503Path}" "$webroot/" >> "$logFile" 2>&1 492 | copyResult="$?" 493 | # verify copy was successful 494 | if [ "$copyResult" = "1" ]; then 495 | # copy was unsuccessful 496 | echo -e "${info}[$(stamp)] -- [INFO] ${warn503} --${normal}" \ 497 | >> "$logFile" 498 | exitWarn+=("[$(stamp)]_5035") 499 | clean503=0 500 | else 501 | # copy was successful 502 | echo -e "${info}[$(stamp)] -- [INFO] 503 error page" \ 503 | "successfully copied to webroot --${normal}" >> "$logFile" 504 | clean503=1 505 | fi 506 | fi 507 | fi 508 | fi 509 | 510 | ### --- End 503 section --- 511 | 512 | 513 | ### Put NextCloud in maintenance mode 514 | ncMaint on 515 | # check if successful 516 | if [ "$maintResult" = "0" ]; then 517 | echo -e "${info}[$(stamp)] -- [INFO] NextCloud now in maintenance mode --" \ 518 | "${normal}" >> "$logFile" 519 | else 520 | exitError+=("[$(stamp)]_100") 521 | cleanup 522 | quit 523 | fi 524 | 525 | 526 | ### Get SQL info from sqlDetails 527 | mapfile -t sqlParams < "$sqlDetails" 528 | 529 | 530 | ### Dump SQL 531 | echo -e "${op}[$(stamp)] Dumping NextCloud SQL database...${normal}" >> "$logFile" 532 | mysqldump --single-transaction -h"${sqlParams[0]}" -u"${sqlParams[1]}" \ 533 | -p"${sqlParams[2]}" "${sqlParams[3]}" > "${sqlDumpDir}/${sqlDumpFile}" \ 534 | 2>> "$logFile" 535 | # verify 536 | dumpResult="$?" 537 | if [ "$dumpResult" = "0" ]; then 538 | echo -e "${ok}[$(stamp)] -- [SUCCESS] SQL dumped successfully --${normal}" \ 539 | >> "$logFile" 540 | else 541 | exitError+=("[$(stamp)]_200") 542 | cleanup 543 | quit 544 | fi 545 | 546 | ### Call borgbackup to copy actual files 547 | echo -e "${op}[$(stamp)] Pre-backup tasks completed, calling borgbackup..." \ 548 | "${normal}" >> "$logFile" 549 | 550 | ## Get borgbackup settings and repo details 551 | # read definition file and map to array variable 552 | mapfile -t borgConfig < "$borgDetails" 553 | ## check if any required borg configuration variables in defintion file are 554 | ## empty and exit with error, otherwise, map array items to variables 555 | # check: borg base directory 556 | echo -e "${op}[$(stamp)] Verifying supplied borg configuration variables..." \ 557 | "${normal}" >> "$logFile" 558 | if [ -z "${borgConfig[0]}" ]; then 559 | exitError+=("[$(stamp)]_210") 560 | cleanup 561 | quit 562 | else 563 | # verify the path actually exists 564 | checkExist fd "${borgConfig[0]}" 565 | checkResult="$?" 566 | if [ "$checkResult" = "1" ]; then 567 | # borg base directory specified could not be found 568 | exitError+=("[$(stamp)]_210") 569 | cleanup 570 | quit 571 | fi 572 | echo -e "${op}[$(stamp)] Borg base dir... OK${normal}" >> "$logFile" 573 | export BORG_BASE_DIR="${borgConfig[0]%/}" 574 | fi 575 | # check: path to SSH keyfile 576 | if [ -z "${borgConfig[1]}" ]; then 577 | exitError+=("[$(stamp)]_211") 578 | cleanup 579 | quit 580 | else 581 | checkExist ff "${borgConfig[1]}" 582 | checkResult="$?" 583 | if [ "$checkResult" = 1 ]; then 584 | # SSH keyfile specified could not be found 585 | exitError+=("[$(stamp)]_211") 586 | cleanup 587 | quit 588 | fi 589 | echo -e "${op}[$(stamp)] Borg SSH key... OK${normal}" >> "$logFile" 590 | export BORG_RSH="ssh -i ${borgConfig[1]}" 591 | fi 592 | # check: name of borg repo 593 | if [ -z "${borgConfig[2]}" ]; then 594 | exitError+=("[$(stamp)]_212") 595 | cleanup 596 | quit 597 | else 598 | echo -e "${op}[$(stamp)] Borg REPO name... OK${normal}" >> "$logFile" 599 | export BORG_REPO="${borgConfig[2]}" 600 | fi 601 | # repo password 602 | if [ -n "${borgConfig[3]}" ]; then 603 | echo -e "${op}[$(stamp)] Borg REPO password... OK${normal}" >> "$logFile" 604 | export BORG_PASSPHRASE="${borgConfig[3]}" 605 | else 606 | exitWarn+=("[$(stamp)]_2111") 607 | # if the password was omitted by mistake, export a dummy password so borg 608 | # fails with an error instead of sitting and waiting for input 609 | export BORG_PASSPHRASE="DummyPasswordSoBorgFails" 610 | fi 611 | # additional files to be backed up 612 | borgXtra="${borgConfig[4]}" 613 | # file with pattern definition for excluded files 614 | borgExclude="${borgConfig[5]}" 615 | # parameters for borg prune 616 | borgPrune="${borgConfig[6]}" 617 | # export: borg remote path (if not blank) 618 | if [ -n "${borgConfig[7]}" ]; then 619 | echo -e "${op}[$(stamp)] Borg REMOTE path... OK${normal}" >> "$logFile" 620 | export BORG_REMOTE_PATH="${borgConfig[7]}" 621 | else 622 | exitWarn+=("[$(stamp)]_2112") 623 | fi 624 | 625 | ## If borgXtra exists, map contents to an array variable 626 | if [ -n "$borgXtra" ]; then 627 | echo -e "${op}[$(stamp)] Processing referenced extra files list for" \ 628 | "borgbackup to include in backup${normal}" >> "$logFile" 629 | checkExist ff "$borgXtra" 630 | checkResult="$?" 631 | if [ "$checkResult" = "0" ]; then 632 | echo -e "${op}[$(stamp)] Found ${lit}${borgXtra}${normal}" >> "$logFile" 633 | mapfile -t xtraFiles < "$borgXtra" 634 | echo -e "${op}[$(stamp)] Processed extra files list for inclusion in" \ 635 | "borgbackup${normal}" >> "$logFile" 636 | else 637 | exitWarn+=("[$(stamp)]_2113") 638 | fi 639 | else 640 | # no extra locations specified 641 | echo -e "${op}[$(stamp)] No additional locations specified for backup." \ 642 | "Only NextCloud data files will be backed up${normal}" >> "$logFile" 643 | exitWarn+=("[$(stamp)]_2116") 644 | fi 645 | 646 | ## Check if borgExclude exists since borg will throw an error if it's missing 647 | if [ -n "$borgExclude" ]; then 648 | checkExist ff "$borgExclude" 649 | checkResult="$?" 650 | if [ "$checkResult" = "0" ]; then 651 | echo -e "${op}[$(stamp)] Found ${lit}${borgExclude}${normal}" \ 652 | >> "$logFile" 653 | else 654 | # file not found, unset the variable so it's like it was not specified 655 | # in the first place and continue with backup 656 | unset borgExclude 657 | exitWarn+=("[$(stamp)]_2114") 658 | fi 659 | else 660 | echo -e "${op}[$(stamp)] Exclusion pattern file not specified." \ 661 | "No exclusions will be processed${normal}" >> "$logFile" 662 | fi 663 | 664 | 665 | ## Export TMPDIR environment variable for borg via python 666 | ## Python requires a writable temporary directory when unpacking borg and 667 | ## executing commands. This defaults to /tmp but many systems mount /tmp with 668 | ## the 'noexec' option for security. Thus, we will use/create a 'tmp' folder 669 | ## within the BORG_BASE_DIR and instruct python to use that instead of /tmp 670 | # check if BORG_BASE_DIR/tmp exists, if not, create it 671 | echo -e "${op}[$(stamp)] Checking for tmp directory at ${lit}${BORG_BASE_DIR}" \ 672 | "${normal}" >> "$logFile" 673 | checkExist fd "$BORG_BASE_DIR/tmp" 674 | checkResult="$?" 675 | if [ "$checkResult" = "1" ]; then 676 | # folder not found 677 | echo -e "${op}[$(stamp)] tmp folder not found... creating${lit}" \ 678 | "${BORG_BASE_DIR}/tmp${normal}" >> "$logFile" 679 | mkdir "$BORG_BASE_DIR/tmp" 2>> "$logFile" 680 | # verify folder created 681 | checkExist fd "$BORG_BASE_DIR/tmp" 682 | checkResult="$?" 683 | if [ "$checkResult" = "0" ]; then 684 | # folder exists 685 | echo -e "${op}[$(stamp)] tmp folder created within borg base directory" \ 686 | "${normal}" >> "$logFile" 687 | else 688 | # problem creating folder and script will exit 689 | exitError+=("[$(stamp)]_215") 690 | cleanup 691 | quit 692 | fi 693 | else 694 | # folder found 695 | echo -e "${op}[$(stamp)] tmp folder found within borg base directory" \ 696 | "${normal}" >> "$logFile" 697 | fi 698 | # export TMPDIR environment variable 699 | export TMPDIR="${BORG_BASE_DIR}/tmp" 700 | 701 | 702 | ## Generate and execute borg 703 | # commandline depends on whether borgExclude is empty or not 704 | if [ -z "$borgExclude" ]; then 705 | # borgExclude is empty 706 | echo -e "${info}[$(stamp)] --[INFO] Executing borg without exclusions --" \ 707 | "${normal}" >> "$logFile" 708 | borg --show-rc create ${borgCreateParams} ::`date +%Y-%m-%d_%H%M%S` \ 709 | "${xtraFiles[@]}" \ 710 | "${sqlDumpDir}" "${ncDataDir}" \ 711 | 2>> "$logFile" 712 | else 713 | # borgExclude is not empty 714 | echo -e "${info}[$(stamp)] --[INFO] Executing borg with exclusions --" \ 715 | "${normal}" >> "$logFile" 716 | borg --show-rc create ${borgCreateParams} --exclude-from "${borgExclude}" \ 717 | ::`date +%Y-%m-%d_%H%M%S` \ 718 | "${xtraFiles[@]}" \ 719 | "${sqlDumpDir}" "${ncDataDir}" \ 720 | 2>> "$logFile" 721 | fi 722 | 723 | ## Check status of borg operation 724 | borgResult="$?" 725 | if [ "$borgResult" -eq 0 ]; then 726 | echo -e "${ok}[$(stamp)] -- [SUCCESS] Borg backup completed successfully --" \ 727 | "${normal}" >> "$logFile" 728 | elif [ "$borgResult" -eq 1 ]; then 729 | exitWarn+=("[$(stamp)]_2200") 730 | elif [ "$borgResult" -ge 2 ]; then 731 | exitError+=("[$(stamp)]_220") 732 | cleanup 733 | quit 734 | else 735 | exitWarn+=("[$(stamp)]_2201") 736 | fi 737 | 738 | ## Generate and execute borg prune 739 | # command depends on whether or not parameters have been defined 740 | if [ -n "$borgPrune" ]; then 741 | # parameters defined 742 | echo -e "${info}[$(stamp)] --[INFO] Executing borg prune operation --" \ 743 | "${normal}" >> "$logFile" 744 | borg prune --show-rc -v ${borgPruneParams} ${borgPrune} \ 745 | 2>> "$logFile" 746 | # check return-status 747 | pruneResult="$?" 748 | if [ "$pruneResult" -eq 0 ]; then 749 | echo -e "${ok}[$(stamp)] -- [SUCCESS] Borg prune completed successfully" \ 750 | "--${normal}" >> "$logFile" 751 | elif [ "$pruneResult" -eq 1 ]; then 752 | exitWarn+=("[$(stamp)]_2210") 753 | elif [ "$pruneResult" -ge 2 ]; then 754 | exitError+=("[$(stamp)]_221") 755 | else 756 | exitWarn+=("[$(stamp)]_2212") 757 | fi 758 | else 759 | # parameters not defined... skip pruning 760 | exitWarn+=("[$(stamp)]_2115") 761 | fi 762 | 763 | 764 | ### borgbackup completed 765 | echo -e "${op}[$(stamp)] Borgbackup completed... begin cleanup" \ 766 | "${normal}" >> "$logFile" 767 | 768 | 769 | ### Exit script 770 | echo -e "${bold}${op}[$(stamp)] ***Normal exit process***${normal}" \ 771 | >> "$logFile" 772 | cleanup 773 | echo -e "${bold}${ok}[$(stamp)] -- [SUCCESS] All processes completed" \ 774 | "successfully --${normal}" >> "$logFile" 775 | quit 776 | 777 | # This code should not be executed since the 'quit' function should terminate 778 | # this script. Therefore, exit with code 99 if we get to this point. 779 | exit 99 780 | -------------------------------------------------------------------------------- /root/NCscripts/excludeLocations.borg: -------------------------------------------------------------------------------- 1 | '/var/nc_data/cache' 2 | sh:/var/nc_data/appdata_*/preview/ 3 | EOF 4 | -------------------------------------------------------------------------------- /root/NCscripts/nc_borg.details: -------------------------------------------------------------------------------- 1 | /var/borgbackup 2 | /var/borgbackup/sshPrivate.key 3 | user@servername.tld:repoName/ 4 | pAsSwOrd 5 | /root/NCscripts/xtraLocations.borg 6 | /root/NCscripts/excludeLocations.borg 7 | --keep-within=7d --keep-daily=30 --keep-weekly=12 --keep-monthly=-1 8 | borg1 -------------------------------------------------------------------------------- /root/NCscripts/nc_sql.details: -------------------------------------------------------------------------------- 1 | localhost 2 | nextcloud 3 | pAsSwOrd 4 | nextcloudDB 5 | -------------------------------------------------------------------------------- /root/NCscripts/xtraLocations.borg: -------------------------------------------------------------------------------- 1 | /etc/fstab 2 | /etc/network/interfaces 3 | /etc/network/interfaces.d/ 4 | /etc/systemd/timesyncd.conf 5 | /etc/profile 6 | /etc/bash.bashrc 7 | /etc/skel/ 8 | /etc/nanorc 9 | /etc/msmtprc 10 | /etc/msmtp_aliases 11 | /etc/apt/sources.list 12 | /etc/apt/sources.list.d/ 13 | /etc/apt/listchanges.conf 14 | /etc/apt/apt.conf.d/50unattended-upgrades 15 | /etc/apt/apt.conf.d/20auto-upgrades 16 | /etc/ssh/ 17 | /etc/logwatch/ 18 | /etc/letsencrypt/ 19 | /etc/fail2ban/fail2ban.local 20 | /etc/fail2ban/jail.local 21 | /etc/fail2ban/filter.d/nextcloud.conf 22 | /etc/fail2ban/jail.d/ 23 | /root/.bashrc 24 | /root/NCscripts/ 25 | /root/.ssh/ 26 | /etc/mysql/my.cnf 27 | /etc/nginx/ 28 | /etc/php/7.2/cli/php.ini 29 | /etc/php/7.2/fpm/php-fpm.conf 30 | /etc/php/7.2/fpm/php.ini 31 | /etc/php/7.2/fpm/pool.d/www.conf 32 | /etc/redis/redis.conf 33 | /usr/share/nginx/html/ --------------------------------------------------------------------------------