#!/usr/bin/sh

# Brief:  encrypt/decrypt files with tripple des at the command line.


# USAGE
# To encrypt a file
# $ source shellcrypt.sh
# $ encrypt_file file.txt
#    This prompts for password and produces file.txt.des3
#    If file.txt.des3 already exists it is moved to ./backup directory. 
#    The file file.txt should be deleted leaving file.txt.des3
#    To decrypt the file back to file.txt
# $ decrypt_file file.txt
#
# DETAILS
# Encrypted files are not deleted by this program.
# Instead a ./backup directory is created and the encryped file is moved
# to it if there is a collision. 
#
# For example the first time you encrypt file.txt it becomes
# file.txt.des3 .  
# Then you decrypt it, edit it and re-encrypt it.
# Since no encrypted data is deleted, if backup directory does not exist it
# is created.  Then file.txt.des3 is renamed and moved to this directory
# ie  file.txt.des3 -> backup/file.txt.des3.Fri_Apr_24_20:13:32_EST_2009
# It is up to you delete the encrypted files.

# Do not use password with space character
# 1:  filename to be encrypted
# 
function encrypt_file
{
  if [ ! -e $1 ]; then 
    echo "error:  $1 does not exits"; 
    return 
  fi

  local encrypt_file_timestamp=`date | sed s/\ /_/g`;
  local encrypt_file_file2=$1.des3
  local encrypt_file_file3=$1.des3.$encrypt_file_timestamp

  # Must backup files and not delete, let the user do this!
  if [ ! -e backup ]; then mkdir backup; fi
  if [ -e $encrypt_file_file2 ]; then 
    mv $encrypt_file_file2 backup/$encrypt_file_file3
  fi

  openssl des3 -salt -in $1 -out $1.des3
  local encrypt_file_res=$?
  if [ $encrypt_file_res != 0 ]; then 
    echo "error:  openssl failed because returned non-zero value"; 
    mv backup/$encrypt_file_file3 $encrypt_file_file2
  else
    rm $1;
  fi

  # TODO issues with this: if openssl fails then file is deleted
  # Further if successful the file is not shredded.
}


# Assume .des3 extension
# 1: filename to be decrypted.  eg decrypt_file pass.csv.des3
function decrypt_file
{
  local arg1=$1;
  local targfile=${arg1%.*}
  echo "xxx${targfile}xxx"
  if [ ! -e $arg1 ]; then echo "error:  file $1 does not exist"; return; fi
  openssl des3 -d -salt -in $arg1 -out $targfile
}



