My various dotfiles

gpg-sqlite.sh 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/bin/sh
  2. # Wrapper for shell editing of GnuPG-encrypted SQLite databases.
  3. #
  4. # Copyright © 2010-2011 Paul Natsuo Kishimoto <mail@paul.kishimoto.name>
  5. # Made available under the GPLv3 (http://www.gnu.org/licenses/gpl-3.0.html)
  6. #
  7. # Usage: gpg-sqlite FILE [RECIPIENT]
  8. #
  9. # gpg-sqlite allows a user to edit a SQLite 3 database encrypted with GnuPG. The
  10. # following steps are taken:
  11. #
  12. # 1. A temporary copy is made of the file to be edited with the owner set to
  13. # the invoking user.
  14. # 2. The SQLirte 3 command-line interface sqlite3(1) is run to edit the
  15. # temporary file.
  16. # 3. Whether or not it has been modified, the temporary file is re-encrypted
  17. # with GnuPG and returned to its original location and the temporary file is
  18. # removed.
  19. #
  20. cleanup () {
  21. # shred and remove the temporary, unencrypted file
  22. shred -u "$TEMPDIR/$BN.$$"
  23. # remove the temporary output; probably don't need to shred, as it's encrypted
  24. rm -f "$TEMPDIR/$BN"
  25. }
  26. # First and only argument is (or should be) the file to edit.
  27. FILE=$1
  28. if [ "$FILE" = "" ]; then
  29. echo "Usage: $(basename $0) filename"
  30. exit 1
  31. fi
  32. if [ "$2" = "" ]; then
  33. # encrypt to self to avoid tedious passphrase retyping
  34. ENCRYPT_FLAGS="-e --default-recipient-self"
  35. # comment out the above and uncomment the following to specify per-file
  36. # passphrases:
  37. #ENCRYPT_FLAGS="-c"
  38. else
  39. ENCRYPT_FLAGS="-e -r $2"
  40. fi
  41. # use a temporary directory in the user's home directory, instead of in /tmp or
  42. # /var/tmp
  43. TEMPDIR=~/.cache/gpg-sqlite
  44. umask 077
  45. mkdir -p $TEMPDIR || exit 1
  46. # strip directories for temporary file names
  47. BN=`basename $FILE`
  48. # if the file exists, try to decrypt it
  49. if [ -e "$FILE" ]; then
  50. while ! gpg <"$FILE" >"$TEMPDIR/$BN.$$"; do
  51. echo "Uh"
  52. done
  53. else
  54. # otherwise assume we're creating a new (empty) file
  55. touch "$TEMPDIR/$BN.$$"
  56. fi
  57. # edit the unencrypted data
  58. if sqlite3 "$TEMPDIR/$BN.$$" .tables >/dev/null 2>&1 ; then
  59. # file actually contains a sqlite database!
  60. sqlite3 "$TEMPDIR/$BN.$$"
  61. else
  62. echo "$(basename $0): $FILE does not contain a sqlite3 database."
  63. cleanup
  64. exit 1
  65. fi
  66. # if the file was modified, re-encrypt and overwrite the original
  67. while ! gpg $ENCRYPT_FLAGS -a <"$TEMPDIR/$BN.$$" >"$TEMPDIR/$BN"; do
  68. echo "Uh, please try again..."
  69. done
  70. cat "$TEMPDIR/$BN" >"$FILE"
  71. cleanup