git-crypt-unlock-all.sh 2.06 KB
Newer Older
Xueshan Feng's avatar
Xueshan Feng committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/bin/bash
#
# Run "git-crypt unlock" with in-repo gpg key, for cloned repo and all submodules in the repo.
# Assuming this repo and all submodule repos are encrypted with your same gpg keyid. 
# If a file name is given at the command line, decrypt this repo using the given symmetric key.
#
# Author: sfeng@stanford.edu
# Date: Sun Apr 17 18:03:13 PDT 2016

function abort() {
  [ -n "$@" ] && { echo "abort: $@"; exit 1; }
}

function skip() {
  [ -n "$@" ] && echo "skip: $@";
}

function verify_gpg_passphrase() {
  echo "Enter the passphrase that will be used to decrypt all in-repo gpg encrypted files, including submodule repos."
  echo "Enter passphrase:"
  read -s passphrase
  [ -z "$passphrase" ] && abort "Empty passphrase"

Xueshan Feng's avatar
Xueshan Feng committed
24
  # Try to encrypt a test file at repo top level with the passphrase, if not successful, exit
Xueshan Feng's avatar
Xueshan Feng committed
25
26
27
28
29
30
31
32
33
34
35
  userids=$(gpg --list-keys | grep pub | grep -oE "/(\w+) " | tr '/' ' ')
  foundkey=1
  echo "test" > /tmp/gpg_test.in
  for i in $userids
  do
    echo $passphrase | \
    gpg -q --sign --local-user $i --passphrase-fd 0 --output /dev/null --yes /tmp/gpg_test.in && \
    echo "The correct passphrase was entered for $i" && foundkey=0 && break
  done
} 

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
function do_unlock() {
  echo unlock $PWD 
  keyfile=$1
  if [ ! -z $keyfile ];
  then
    git-crypt unlock $keyfile
  else
    expect <<EOF
spawn git-crypt unlock
expect "Enter passphrase:"
send "$passphrase\r";
expect eof
EOF
  fi
}

Xueshan Feng's avatar
Xueshan Feng committed
52
# MAIN
Xueshan Feng's avatar
Xueshan Feng committed
53
54
keyfile=${1:-''}
if [ -z $keyfile ];
Xueshan Feng's avatar
Xueshan Feng committed
55
56
57
58
59
60
61
then
  verify_gpg_passphrase
  [ $foundkey -ne 0 ] && abort "Unable to decrypt."
else
  [ ! -f $keyfile ] && abort "unable to read $keyfile."
fi

62
63
64
65
# unlock current repo
do_unlock $keyfile

# unlock submodules
Xueshan Feng's avatar
Xueshan Feng committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
modules=$(git submodule status)
[ -z "$modules" ] && abort "No submodules"

git submodule status | while read i
do
  m=$(echo $i | cut -d' ' -f2)
  if echo $i | grep ^- > /dev/null 2>&1 ;
  then
    skip "Skipping $m; Please update module with: git submodule init $m && git submodule update $m."
    continue
  else
    ( echo "Checking out $i master branch"
      cd $m
      git checkout master
80
      do_unlock $keyfile
Xueshan Feng's avatar
Xueshan Feng committed
81
82
83
    )
  fi
done