move_to_hierarchy.rb: fix typo
[cmccabe-bin] / passtool.sh
1 #!/usr/bin/env bash
2
3 die() {
4     echo $1
5     exit 1
6 }
7
8 usage() 
9 {
10     cat <<EOF
11 $0: a tool for dealing with passwords.
12
13 Flags:
14 -f [path]: specify the password file to use.
15 -h: this help message.
16 -s [pattern]: search for the given pattern
17
18 Environment variables:
19 EDITOR: the editor to use.
20 EOF
21 }
22
23 TEMPDIR="/dev/shm/passtool.$$.$RANDOM"
24 EDITOR=${EDITOR:-vi}
25 mkdir -p "${TEMPDIR}" || die "failed to mkdir ${TEMPDIR}"
26 TEMPFILE="${TEMPDIR}/temp"
27 TEMPFILE_ENC="${TEMPDIR}/temp.nc"
28 trap "rm -rf ${TEMPDIR}; exit" EXIT
29 #chmod 007 "${TEMPDIR}" || die "failed to chmod ${TEMPDIR}"
30
31 SEARCH_PATTERN=""
32 while getopts  "f:hs:" flag; do
33     case $flag in
34         f)  PASSWORD_PATH="${OPTARG}";;
35         h)  usage; exit 0;;
36         s)  SEARCH_PATTERN="${OPTARG}";;
37         *)  echo; usage; exit 1;;
38     esac
39 done
40
41 [[ -z ${PASSWORD_PATH} ]] && die "You must specify a password file path with -f"
42 [[ -f ${PASSWORD_PATH} ]] || die "No regular file found at ${PASSWORD_PATH}"
43
44 if [[ -z ${PASSWORD} ]]; then
45     read -s -p "enter password: " PASSWORD
46 fi
47 if openssl enc -d -aes-256-ecb -k "${PASSWORD}" \
48         < "${PASSWORD_PATH}" > "${TEMPFILE}"; then
49     if [[ -z ${SEARCH_PATTERN} ]]; then
50         ${EDITOR} "${TEMPFILE}"
51         openssl enc -aes-256-ecb -k "${PASSWORD}" -salt \
52                     < "${TEMPFILE}" > "${TEMPFILE_ENC}" ||
53             die "Re-encryption failed.  Changes lost."
54         mv -f "${TEMPFILE_ENC}" "${PASSWORD_PATH}" || \
55             die "failed to move ${TEMPFILE_ENC} to ${PASSWORD_PATH}: changes lost."
56     else
57         echo
58         egrep ${SEARCH_PATTERN} "${TEMPFILE}"
59     fi
60 else
61     die "Failed to decrypt ${PASSWORD_PATH}.  Was the password correct?"
62 fi