[
  {
    "path": ".gitignore",
    "content": ".cider-repl-history\n.clj-kondo/\n.cpcache/\n"
  },
  {
    "path": "LICENSE",
    "content": "THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC\nLICENSE (\"AGREEMENT\"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM\nCONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.\n\n1. DEFINITIONS\n\n\"Contribution\" means:\n\na) in the case of the initial Contributor, the initial code and\ndocumentation distributed under this Agreement, and\n\nb) in the case of each subsequent Contributor:\n\ni) changes to the Program, and\n\nii) additions to the Program;\n\nwhere such changes and/or additions to the Program originate from and are\ndistributed by that particular Contributor. A Contribution 'originates' from\na Contributor if it was added to the Program by such Contributor itself or\nanyone acting on such Contributor's behalf. Contributions do not include\nadditions to the Program which: (i) are separate modules of software\ndistributed in conjunction with the Program under their own license\nagreement, and (ii) are not derivative works of the Program.\n\n\"Contributor\" means any person or entity that distributes the Program.\n\n\"Licensed Patents\" mean patent claims licensable by a Contributor which are\nnecessarily infringed by the use or sale of its Contribution alone or when\ncombined with the Program.\n\n\"Program\" means the Contributions distributed in accordance with this\nAgreement.\n\n\"Recipient\" means anyone who receives the Program under this Agreement,\nincluding all Contributors.\n\n2. GRANT OF RIGHTS\n\na) Subject to the terms of this Agreement, each Contributor hereby grants\nRecipient a non-exclusive, worldwide, royalty-free copyright license to\nreproduce, prepare derivative works of, publicly display, publicly perform,\ndistribute and sublicense the Contribution of such Contributor, if any, and\nsuch derivative works, in source code and object code form.\n\nb) Subject to the terms of this Agreement, each Contributor hereby grants\nRecipient a non-exclusive, worldwide, royalty-free patent license under\nLicensed Patents to make, use, sell, offer to sell, import and otherwise\ntransfer the Contribution of such Contributor, if any, in source code and\nobject code form.  This patent license shall apply to the combination of the\nContribution and the Program if, at the time the Contribution is added by the\nContributor, such addition of the Contribution causes such combination to be\ncovered by the Licensed Patents. The patent license shall not apply to any\nother combinations which include the Contribution. No hardware per se is\nlicensed hereunder.\n\nc) Recipient understands that although each Contributor grants the licenses\nto its Contributions set forth herein, no assurances are provided by any\nContributor that the Program does not infringe the patent or other\nintellectual property rights of any other entity. Each Contributor disclaims\nany liability to Recipient for claims brought by any other entity based on\ninfringement of intellectual property rights or otherwise. As a condition to\nexercising the rights and licenses granted hereunder, each Recipient hereby\nassumes sole responsibility to secure any other intellectual property rights\nneeded, if any. For example, if a third party patent license is required to\nallow Recipient to distribute the Program, it is Recipient's responsibility\nto acquire that license before distributing the Program.\n\nd) Each Contributor represents that to its knowledge it has sufficient\ncopyright rights in its Contribution, if any, to grant the copyright license\nset forth in this Agreement.\n\n3. REQUIREMENTS\n\nA Contributor may choose to distribute the Program in object code form under\nits own license agreement, provided that:\n\na) it complies with the terms and conditions of this Agreement; and\n\nb) its license agreement:\n\ni) effectively disclaims on behalf of all Contributors all warranties and\nconditions, express and implied, including warranties or conditions of title\nand non-infringement, and implied warranties or conditions of merchantability\nand fitness for a particular purpose;\n\nii) effectively excludes on behalf of all Contributors all liability for\ndamages, including direct, indirect, special, incidental and consequential\ndamages, such as lost profits;\n\niii) states that any provisions which differ from this Agreement are offered\nby that Contributor alone and not by any other party; and\n\niv) states that source code for the Program is available from such\nContributor, and informs licensees how to obtain it in a reasonable manner on\nor through a medium customarily used for software exchange.\n\nWhen the Program is made available in source code form:\n\na) it must be made available under this Agreement; and\n\nb) a copy of this Agreement must be included with each copy of the Program.\n\nContributors may not remove or alter any copyright notices contained within\nthe Program.\n\nEach Contributor must identify itself as the originator of its Contribution,\nif any, in a manner that reasonably allows subsequent Recipients to identify\nthe originator of the Contribution.\n\n4. COMMERCIAL DISTRIBUTION\n\nCommercial distributors of software may accept certain responsibilities with\nrespect to end users, business partners and the like. While this license is\nintended to facilitate the commercial use of the Program, the Contributor who\nincludes the Program in a commercial product offering should do so in a\nmanner which does not create potential liability for other Contributors.\nTherefore, if a Contributor includes the Program in a commercial product\noffering, such Contributor (\"Commercial Contributor\") hereby agrees to defend\nand indemnify every other Contributor (\"Indemnified Contributor\") against any\nlosses, damages and costs (collectively \"Losses\") arising from claims,\nlawsuits and other legal actions brought by a third party against the\nIndemnified Contributor to the extent caused by the acts or omissions of such\nCommercial Contributor in connection with its distribution of the Program in\na commercial product offering.  The obligations in this section do not apply\nto any claims or Losses relating to any actual or alleged intellectual\nproperty infringement. In order to qualify, an Indemnified Contributor must:\na) promptly notify the Commercial Contributor in writing of such claim, and\nb) allow the Commercial Contributor tocontrol, and cooperate with the\nCommercial Contributor in, the defense and any related settlement\nnegotiations. The Indemnified Contributor may participate in any such claim\nat its own expense.\n\nFor example, a Contributor might include the Program in a commercial product\noffering, Product X. That Contributor is then a Commercial Contributor. If\nthat Commercial Contributor then makes performance claims, or offers\nwarranties related to Product X, those performance claims and warranties are\nsuch Commercial Contributor's responsibility alone. Under this section, the\nCommercial Contributor would have to defend claims against the other\nContributors related to those performance claims and warranties, and if a\ncourt requires any other Contributor to pay any damages as a result, the\nCommercial Contributor must pay those damages.\n\n5. NO WARRANTY\n\nEXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON\nAN \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER\nEXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR\nCONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A\nPARTICULAR PURPOSE. Each Recipient is solely responsible for determining the\nappropriateness of using and distributing the Program and assumes all risks\nassociated with its exercise of rights under this Agreement , including but\nnot limited to the risks and costs of program errors, compliance with\napplicable laws, damage to or loss of data, programs or equipment, and\nunavailability or interruption of operations.\n\n6. DISCLAIMER OF LIABILITY\n\nEXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY\nCONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION\nLOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE\nEXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY\nOF SUCH DAMAGES.\n\n7. GENERAL\n\nIf any provision of this Agreement is invalid or unenforceable under\napplicable law, it shall not affect the validity or enforceability of the\nremainder of the terms of this Agreement, and without further action by the\nparties hereto, such provision shall be reformed to the minimum extent\nnecessary to make such provision valid and enforceable.\n\nIf Recipient institutes patent litigation against any entity (including a\ncross-claim or counterclaim in a lawsuit) alleging that the Program itself\n(excluding combinations of the Program with other software or hardware)\ninfringes such Recipient's patent(s), then such Recipient's rights granted\nunder Section 2(b) shall terminate as of the date such litigation is filed.\n\nAll Recipient's rights under this Agreement shall terminate if it fails to\ncomply with any of the material terms or conditions of this Agreement and\ndoes not cure such failure in a reasonable period of time after becoming\naware of such noncompliance. If all Recipient's rights under this Agreement\nterminate, Recipient agrees to cease use and distribution of the Program as\nsoon as reasonably practicable. However, Recipient's obligations under this\nAgreement and any licenses granted by Recipient relating to the Program shall\ncontinue and survive.\n\nEveryone is permitted to copy and distribute copies of this Agreement, but in\norder to avoid inconsistency the Agreement is copyrighted and may only be\nmodified in the following manner. The Agreement Steward reserves the right to\npublish new versions (including revisions) of this Agreement from time to\ntime. No one other than the Agreement Steward has the right to modify this\nAgreement. The Eclipse Foundation is the initial Agreement Steward. The\nEclipse Foundation may assign the responsibility to serve as the Agreement\nSteward to a suitable separate entity. Each new version of the Agreement will\nbe given a distinguishing version number. The Program (including\nContributions) may always be distributed subject to the version of the\nAgreement under which it was received. In addition, after a new version of\nthe Agreement is published, Contributor may elect to distribute the Program\n(including its Contributions) under the new version. Except as expressly\nstated in Sections 2(a) and 2(b) above, Recipient receives no rights or\nlicenses to the intellectual property of any Contributor under this\nAgreement, whether expressly, by implication, estoppel or otherwise. All\nrights in the Program not expressly granted under this Agreement are\nreserved.\n\nThis Agreement is governed by the laws of the State of New York and the\nintellectual property laws of the United States of America. No party to this\nAgreement will bring a legal action under this Agreement more than one year\nafter the cause of action arose. Each party waives its rights to a jury trial\nin any resulting litigation.\n"
  },
  {
    "path": "LaunchAgent/README.md",
    "content": "# Example launchd.plist\n\nThis is an example of a configuration file that goes in `~/Library/LaunchAgents/` on the Mac. See the main page for `launchd.plist` for more about the format.\n"
  },
  {
    "path": "LaunchAgent/backup.workmac.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n    <key>Label</key>\n    <string>backup.workmac</string>\n    <key>ProgramArguments</key>\n    <array>\n        <string>/usr/bin/ssh</string>\n        <string>einstein.local</string>\n        <string>/media/backup/backup-workmac.sh</string>\n    </array>\n    <key>KeepAlive</key>\n    <dict>\n      <key>SuccessfulExit</key>\n      <false/>\n    </dict>\n    <key>ThrottleInterval</key>\n    <integer>60</integer>\n    <key>StartCalendarInterval</key>\n    <dict>\n      <key>Minute</key>\n      <integer>0</integer>\n      <key>Hour</key>\n      <integer>11</integer>\n    </dict>\n    <key>StandardOutPath</key>\n    <string>/usr/local/var/log/backup-workmac.log</string>\n    <key>StandardErrorPath</key>\n    <string>/usr/local/var/log/backup-workmac.log</string>\n</dict>\n</plist>\n"
  },
  {
    "path": "README.md",
    "content": "# My backup scripts\n\nThese are my current scripts for backing up three laptops around the house to a desktop PC. It is also a small experiment in using [babashka](https://github.com/babashka/babashka), a scripting flavour of the Clojure language.\n\nI had never used babaskha, so this is very unlikely to be a good example for anyone else. For much better information and examples, see babashka's [online book](https://book.babashka.org/#introduction).\n\n## Main goals and outcomes\n\nThe main reason I was revisiting my home backup scripts it that we've transitioned over the years from a household of two or three standard PCs, to one with three laptops.\n\nI used to mirror my family's home directories to an external drive. I used Time Machine on the Mac and [cron](http://manpages.ubuntu.com/manpages/focal/en/man3/cron.3tcl.html) and [rsync](http://manpages.ubuntu.com/manpages/focal/man1/rsync.1.html) on Linux. That mostly just worked.\n\nLaptops are a new challenge, though. You can't just go around with an external drive hanging off them. They're often sleeping, with the lid down, on a sofa somewhere and (unless it's the work laptop) used intermittently.\n\nMy solution, at the moment, is to back up centrally (using the [server-side script](src/eamonnsullivan/backup.clj) that is the main focus of this repo), but have the laptops initiate the process by running small shell scripts over ssh. I'm using [anacron](http://manpages.ubuntu.com/manpages/focal/man8/anacron.8.html) on Ubuntu and launchctl/launchd on the Mac to configure the laptops to back themselves up once a day.\n\n### Why do I still need backups?\n\nThat's a question worth considering. Why not just use Dropbox, Google Drive or whatever Apple's pushing these days? I do actually already use these things, plus Github for all of my source code.\n\nBut these aren't back up systems. If I accidentally delete an important file, for example, it's very shortly gone from these systems as well.\n\nAlso, my wife (who doesn't use Dropbox or anything like it) keeps her entire digital life (word processing documents, presentation, spreadsheets, etc.) on a Thinkpad running Ubuntu. She counts on me to keep those safe. (Well, actually, she just assumes they are safe... I'm the IT Guy in the house and it's my job to worry about such things.)\n\nMostly, though, I like having control over my own data and I want to understand how it is being stored and moved around. I will probably extend this system to the cloud in the future -- periodically sending monthly backups offsite -- but I will likely use S3 on my own AWS account for that, keeping it under my understanding and control.\n\n## Prerequisites\n\nYou'll need a PC that's either always on or reliably turned on when it's needed. It will need plenty of disk storage. A Raspberry Pi 4 with an attached USB disk is what I use at the moment. I installed the ARM port of Ubuntu server on it, and babashka now has ARM support as well.\n\nI use a 1TB SSD USB disk, mounted permanently at /media/backup. Here's [one random guide](https://www.techrepublic.com/article/how-to-properly-automount-a-drive-in-ubuntu-linux/) on how to mount an external disk automatically on boot.\n\nYou will also need to set up password-less SSH access, both from the back up PC to the devices, and from the devices to the back up PC. This will allow the back up PC to run rsync to the devices, and also allow to the devices to kick off the process by running a small shell script via SSH. There are a lot of guides on the Internet for this, such as [this one](https://linuxize.com/post/how-to-setup-passwordless-ssh-login/).\n\nI don't use Windows at the moment and don't really mount network drives, either. That might be a good alternative to consider.\n\n## Back up approach\n\nI used to just mirror everyone's home directory on another device. Just periodically run rsync and sync all of the files to the external hard drive. This works, but it has a couple of disadvantages. One important disadvantage is that if you delete a file on Tuesday and discover on Thursday that you really actually needed that file, it's probably now gone from the back up, as well.\n\nSo, instead I took a cue from Apple's Time Machine and take advantage of hard links, a relatively underused facility in most Unix based file systems. Basically, it just gives the file another name, somewhere else. If you delete one of the names, the same file still lives under the other name. And hard links don't take up any extra space (or hardly any).\n\nI also mitigate against creeping bad sectors (which happen even on SSDs) by periodically starting over again with a fresh, full back up.\n\nThe basic algorithm:\n\n 1. Run rsync to sync the files from one place to another.\n 1. Make a hard link of all of the files to another location on the file system, under a directory with the date in the name.\n 1. Check the remaining free space on the back up device and compare it with the last full back I just did. If free space is less than twice the size of the last backup, I start removing the oldest backups (the ones created in the last step) until I have that much remaining.\n 1. Once a month, I start a new full back up from scratch. This is to guard against bad sectors in the disk, which can make older files become unreadable, and you would never know until you tried to restore it.\n\n## Example scripts\n\n * [LaunchAgent on the Mac laptop](LaunchAgent/)\n * [Anacron script for the Ubuntu laptops](anacron/)\n * [Starter script on the server](server/)\n * [Main back up script](src/eamonnsullivan/backup.clj)\n\n## License\n\nCopyright © 2021 Eamonn Sullivan\n\nDistributed under the Eclipse Public License version 1.0.\n"
  },
  {
    "path": "anacron/README.md",
    "content": "# Example Anacron script\n\nThis is an example of a script you would place in `/etc/cron.daily` to initiate the back up. The laptop will try running this script once a day, when it wakes up.\n\nFor this to work, you will need password-less access to the back up PC over ssh.\n"
  },
  {
    "path": "anacron/backup",
    "content": "#!/bin/sh\n\n/usr/bin/ssh einstein.local /media/backup/backup-thinkpad.sh\nEXITVALUE=$?\nif [ $EXITVALUE != 0 ]; then\n    /usr/bin/logger -t backup \"ALERT exited abnormally with [$EXITVALUE]\"\nfi\nexit $EXITVALUE\n"
  },
  {
    "path": "server/README.md",
    "content": "# Sample Start script for the service\n\nThis is an example of a very short bash script that sits on the service. It's only real purpose is to make the ssh command from the laptop simpler. The laptops just call a script like this, which in turn calls the main back up script.\n"
  },
  {
    "path": "server/backup-thinkpad.sh",
    "content": "#!/usr/bin/env bash\n\n/media/backup/backup.clj root@thinkpad.local:/home thinkpad >>/var/log/backups/backup_thinkpad.log 2>&1\n"
  },
  {
    "path": "src/eamonnsullivan/backup.clj",
    "content": "#!/usr/bin/env bb\n\n(ns eamonnsullivan.backup\n  \"A wrapper around rsync that manages multiple backups of multiple\n  hosts. After each backup, it creates a hard link (effectively\n  creating a snapshot of the current difference since the previous\n  backup) and checks the free space available on the storage\n  device. If free space is less than double the size of the most\n  recent backup, we remove older backups.\n\n  At the start of a new month, we begin a fresh backup. This is to\n  avoid any potential issues with bad sectors.\n\n  Usage: <backup-from> <name-of-backup>\n\n  Examples: backup.clj root@thinkpad.local:/home thinkpad\n            backup.clj sullie09@mc-s105910.local:~ workmac\"\n  {:author \"Eamonn Sullivan\"}\n  (:import (java.time.format DateTimeFormatter)\n           (java.time LocalDateTime))\n  (:require [clojure.java.io :as io]\n            [clojure.java.shell :refer [sh]]\n            [clojure.string :as string]\n            [babashka.fs :as fs]))\n\n(def ^:dynamic *base-path* \"/media/backup\")\n(def ^:dynamic *rsync-command* [\"rsync\" \"-avzpH\" \"--partial\" \"--delete\" \"--exclude-from=/etc/rsync-backup-excludes.txt\"])\n\n(def month-formatter (DateTimeFormatter/ofPattern \"yyyy-MM\"))\n(def date-time-formatter (DateTimeFormatter/ofPattern \"yyyy-MM-dd_HH-mm-s\"))\n\n(defn retry\n  \"Retry function f, n times and check whether it succeeded with the\n  predicate success?\"\n  ([f success? num-retries]\n   (retry f success? num-retries 30000))\n  ([f success? num-retries wait-time]\n  (if (zero? num-retries)\n    (f)\n    (let [result (f)]\n      (if (not (success? result))\n        (do\n          (println (format \"Function failed with error [%s], retrying\" (:err result)))\n          (Thread/sleep wait-time)\n          (retry f success? (dec num-retries) wait-time))\n        result)))))\n\n(defn get-current-month\n  \"Get a string that includes the year and month.\"\n  []\n  (.format (LocalDateTime/now) month-formatter))\n\n(defn link\n  \"Create a hard link from path to target.\"\n  [path target]\n  (sh \"cp\" \"-al\" path target))\n\n(defn write-check-month-file\n  \"Write out the current year and month into a backup-specific file that\n  we can compare against. Used so that we can more easily tell when\n  we've changed months since the last backup.\"\n  [content backup]\n  (spit (format \"%s/checkMonth_%s.txt\" *base-path* backup) content))\n\n(defn new-month?\n  \"Predicate: Given the contents of this backup's checkMonth file, are\n  we creating the first back up of this month?\"\n  [last]\n  (let [now (get-current-month)]\n    (not= now last)))\n\n(defn delete-backup\n  \"Remove the current named backup. This is normally done when we are\n  starting the first backup of the month.\"\n  [backup]\n  (let [target (format \"%s/%s\" *base-path* backup)]\n    (println \"Removing: \" target)\n    (fs/delete-tree target)))\n\n(defn get-backup-usage\n  \"How much disk space is this backup using?\"\n  [backup]\n  (let [path (format \"%s/%s\" *base-path* backup)\n        fsize (sh \"du\" \"-sb\" path)\n        outsize (first (string/split (:out fsize) #\"\\s\"))]\n    (println \"Size of current backup: \" outsize)\n    (bigint (string/trim outsize))))\n\n(defn check-month\n  \"Check whether we've started a new month. If we have, create a new\n  backup from scratch.\"\n  [backup]\n  (let [check (io/as-file (format \"%s/checkMonth_%s.txt\" *base-path* backup))\n        last (if (.exists check) (slurp check) nil)]\n    (when (new-month? last)\n      (println (format \"Starting a new monthly backup set for %s\" (format \"%s/%s\" *base-path* backup)))\n      (let [backupdir (io/as-file (format \"%s/%s\" *base-path* backup))]\n        (when (.exists backupdir)\n          (println \"Existing backup found, so removing...\"  )\n          (delete-backup backup))\n        (io/make-parents (format \"%s/.keep\" (.getPath backupdir))))\n      (write-check-month-file (get-current-month) backup))))\n\n(defn make-hard-link\n  \"Make a hard link of the current back up.\"\n  [backup bdir]\n  (let [linkto (format \"%s/old/%s\" *base-path* bdir)\n        linkfrom (format \"%s/%s/\" *base-path* backup)]\n    (io/make-parents (io/as-file linkto))\n    (link linkfrom linkto)))\n\n(defn oldest-dir\n  \"Find the oldest (least most recently modified) directory in parent.\"\n  [parent]\n  (let [dirs (.listFiles (io/as-file parent))\n        sorted (sort-by #(.lastModified %) dirs)]\n    (first sorted)))\n\n(defn delete-oldest-backup\n  \"Find the oldest backup hard linked in <base-path>/old and remove it.\"\n  []\n  (let [dir (.getName (oldest-dir (format \"%s/old\" *base-path*)))]\n    (println \"Oldest backup: \" dir)\n    (if (not (nil? dir))\n      (sh \"bash\" \"-c\" (format \"rm -rf %s/old/%s\" *base-path* dir))\n      (throw (ex-info \"Could not remove any more old backups!\" {:base-path *base-path*})))))\n\n(defn check-free\n  \"Check the free space on the backup device. If it isn't at\n  least twice the size of the last (current) backup, delete the oldest\n  backup and try again. Repeat until enough space.\"\n  [backup]\n  (let [curr-used (get-backup-usage backup)\n        est-need (* curr-used 2)]\n    (println \"The current back up is using \" curr-used)\n    (println \"We're estimating that we need: \" est-need)\n    (loop [curr-free (.getFreeSpace (io/as-file *base-path*))]\n      (println \"Current free space on this device: \" curr-free)\n      (if (> curr-free est-need)\n        true\n        (do\n          (println \"Not enough disk space available, so removing the oldest backup.\")\n          (delete-oldest-backup)\n          (recur (.getFreeSpace (io/as-file *base-path*))))))))\n\n(defn rsync!\n  \"The actual rsync of files from somewhere, to somewhere else. This\n  returns a map of the :exit code, standard output (:out) and any :err\n  output.\"\n  [backup-from backup-to]\n  (let [rsync-command (into [] (conj *rsync-command* backup-from (format \"%s/%s\" *base-path* backup-to)))]\n    (println \"Starting rsync: \" (string/join \" \" rsync-command))\n    (apply sh rsync-command)))\n\n(defn -main\n  []\n  (let [[backup-from backup-to] *command-line-args*]\n    (when (or (not backup-from) (not backup-to))\n      (println \"Usage: <user@hostname.local:/home> <backup-name>\")\n      (System/exit 1))\n    (println (format \"Starting backup of %s to %s on %s\" backup-from backup-to (.toString (LocalDateTime/now))))\n    (check-month backup-to)\n    (let [result (retry #(rsync! backup-from backup-to) #(= 0 (:exit %)) 3)]\n      (if (= 0 (:exit result))\n        (do\n          (println (:out result))\n          (make-hard-link backup-to (format \"%s-%s\" (.format (LocalDateTime/now) date-time-formatter) backup-to))\n          (check-free backup-to)\n          (println (format \"Successfully finished backup of %s at %s\" backup-from (.toString (LocalDateTime/now)))))\n        (do\n          (println (format \"The backup of %s ended in an error: %s\" backup-from (:err result)))\n          (println \"Not making a hard link or checking free space.\")))\n      (System/exit (:exit result)))))\n\n(when (= *file* (System/getProperty \"babashka.file\"))\n  (-main))\n\n\n(comment\n  (import (java.time.format DateTimeFormatter))\n  (import (java.time LocalDateTime))\n  (require '[clojure.java.io :as io])\n  (require '[clojure.java.shell :refer [sh]])\n  (def *base-path* \"/home/eamonn/backup-test\")\n  )\n"
  },
  {
    "path": "test/eamonnsullivan/backup_test.clj",
    "content": "#!/usr/bin/env bb\n\n(ns eamonnsullivan.backup-test\n  {:author \"Eamonn Sullivan\"}\n  (:import (java.time LocalDateTime))\n  (:require [eamonnsullivan.backup :as sut]\n            [babashka.fs :as fs]\n            [clojure.java.io :as io]\n            [clojure.test :as t :refer [deftest testing is]]))\n\n(def cwd (fs/real-path \".\"))\n\n(defn temp-dir []\n  (-> (fs/create-temp-dir)\n      (fs/delete-on-exit)))\n\n(deftest test-new-month?\n  (with-redefs [sut/get-current-month (fn [] \"2020-01\")]\n    (testing \"compares the year and month\"\n      (is (= false\n             (sut/new-month? \"2020-01\"))))))\n\n(deftest retry-test\n  (testing \"should retry the specified number of times\"\n    (is (= 4 ;; first, then three retries.\n           (let [attempts-count (volatile! 0)\n                 _ (sut/retry #(vswap! attempts-count inc) :continue 3 100)]\n             @attempts-count))))\n  (testing \"should stop retrying when predicate returns true\"\n    (is (= 3\n           (let [attempts-count (volatile! 0)\n                 _ (sut/retry #(vswap! attempts-count inc) (fn [_] (< 2 @attempts-count)) 5 100)]\n             @attempts-count)))))\n\n(deftest test-link\n  (let [tmp-dir (temp-dir)\n        dir (str (fs/create-dir (fs/path tmp-dir \"foo\")))\n        _ (spit (fs/file tmp-dir \"foo/\" \"dudette.txt\") \"some content\")\n        linkto (str tmp-dir \"/bar\")\n        _ (sut/link dir linkto)]\n    (is (.exists (fs/file tmp-dir \"foo\")))\n    (is (.exists (fs/file tmp-dir \"bar\")))\n    (is (.exists (fs/file tmp-dir \"bar/\" \"dudette.txt\")))\n    (is (= (slurp (fs/file tmp-dir \"foo/\" \"dudette.txt\"))\n           (slurp (fs/file tmp-dir \"bar/\" \"dudette.txt\"))))\n    (is (= 2 (fs/get-attribute (fs/file tmp-dir \"bar/\" \"dudette.txt\")\n                               \"unix:nlink\")))))\n\n(deftest test-delete-backup\n  (let [tmp-dir (temp-dir)\n        _ (fs/create-dir (fs/path tmp-dir \"foo\"))\n        _ (fs/create-dir (fs/path tmp-dir \"bar\"))\n        _ (spit (fs/file tmp-dir \"bar/\" \"something.txt\") \"with content\")\n        _ (spit (fs/file tmp-dir \"foo/\" \"dude.txt\") \"some content\")]\n    (binding [sut/*base-path* tmp-dir]\n      (sut/delete-backup \"foo\")\n      (is (.exists (fs/file tmp-dir \"bar\")))\n      (is (not (.exists (fs/file tmp-dir \"foo\")))))))\n\n(deftest test-get-backup-usage\n  (let [tmp-dir (temp-dir)\n        _ (fs/create-dir (fs/path tmp-dir \"foo\"))\n        _ (spit (fs/file tmp-dir \"foo/\" \"content.txt\") \"123\\n\")]\n    (binding [sut/*base-path* tmp-dir]\n      (is (= 4100\n             (sut/get-backup-usage \"foo\"))))))\n\n(deftest test-check-month\n  (let [tmp-dir (temp-dir)\n        _ (fs/create-dir (fs/path tmp-dir \"foo\"))\n        _ (spit (fs/file tmp-dir \"foo/\" \"content.txt\") \"123\")\n        _ (spit (fs/file tmp-dir \"checkMonth_foo.txt\") \"456\")]\n    (binding [sut/*base-path* tmp-dir]\n      (with-redefs [sut/new-month? (fn [_] false)]\n        (testing \"does not delete current backup if the month hasn't changed\"\n          (sut/check-month \"foo\")\n          (is (.exists (fs/file tmp-dir \"foo\")))))\n      (with-redefs [sut/new-month? (fn [_] true)\n                    sut/get-current-month (fn [] \"789\")]\n        (testing \"removes current backup and writes new checkMonth file when month changes\"\n          (sut/check-month \"foo\")\n          (is (not (.exists (fs/file tmp-dir \"foo/\" \"content.txt\"))))\n          (is (= \"789\"\n                 (slurp (fs/file tmp-dir \"checkMonth_foo.txt\")))))))))\n\n(deftest test-make-hard-link\n  (let [tmp-dir (temp-dir)\n        _ (fs/create-dir (fs/path tmp-dir \"foo\"))\n        _ (spit (fs/file tmp-dir \"foo/\" \"content.txt\") \"123\")]\n    (binding [sut/*base-path* tmp-dir]\n      (testing \"makes a hard-link under /old of the current backup\"\n        (sut/make-hard-link \"foo\" \"foo-123\")\n        (is (.exists (fs/file tmp-dir \"old/foo-123/\" \"content.txt\")))))))\n\n(deftest test-oldest-dir\n  ;; My slower Linux system seems to need the sleeps...\n  (let [tmp-dir (temp-dir)\n        _ (fs/create-dir (fs/path tmp-dir \"one\"))\n        _ (Thread/sleep 10)\n        _ (fs/create-dir (fs/path tmp-dir \"two\"))\n        _ (Thread/sleep 10)\n        _ (fs/create-dir (fs/path tmp-dir \"three\"))]\n    (testing \"should find oldest directory by last modified\"\n      (is (= (fs/path tmp-dir \"one\")\n             (fs/path (sut/oldest-dir (str tmp-dir))))))))\n\n(deftest test-delete-oldest-backup\n  (let [tmp-dir (temp-dir)\n        _ (fs/create-dir (fs/path tmp-dir \"old\"))\n        _ (fs/create-dir (fs/path tmp-dir \"old/\" \"one\"))\n        _ (Thread/sleep 10)\n        _ (fs/create-dir (fs/path tmp-dir \"old/\" \"two\"))\n        _ (Thread/sleep 10)\n        _ (fs/create-dir (fs/path tmp-dir \"old/\" \"three\"))]\n    (testing \"should remove the old directory under /old\"\n      (binding [sut/*base-path* tmp-dir]\n        (sut/delete-oldest-backup)\n        (is (not (.exists (fs/file tmp-dir \"old/\" \"one\"))))\n        (is (.exists (fs/file tmp-dir \"old/\" \"two\")))\n        (is (.exists (fs/file tmp-dir \"old/\" \"three\")))))))\n"
  },
  {
    "path": "test_runner.clj",
    "content": "#!/usr/bin/env bb\n\n(require '[clojure.test :as t]\n         '[babashka.classpath :as cp])\n\n(cp/add-classpath \"src:test\")\n\n(require 'eamonnsullivan.backup-test)\n\n(def test-results\n  (t/run-tests 'eamonnsullivan.backup-test))\n\n(def failures-and-errors\n  (let [{:keys [:fail :error]} test-results]\n    (+ fail error)))\n\n(System/exit failures-and-errors)\n"
  }
]