#!/bin/bash
#
# Bitcoin private key import helper (c)2012 ElasticNinja
# bitcoin:1NinjaRFABUh48pwL5CdAYgnt8bTPnsuu4
#
# Requires bitcoin client running in server mode. If you don't already have this
# then edit ~/.bitcoin/bitcoin.conf and add following three lines:
# rpcuser=<some random username>
# rpcpassword=<some random password>
# server=1
#
# After modifying restart your bitcoin client. When you are finished adding keys
# you can remove those lines from configuration.
#
#

function unlock_wallet()
{
	bitcoind walletpassphrase "$1" "$2"
}

function import_key()
{
	bitcoind importprivkey "$1" "$2"
}

function fatal()
{
  echo $1
  exit 1
}

function usage()
{
       echo "Usage: bitkeyimport [-P|-p passphrase] [-l label] -k privkey"
       echo ""
       echo "-h    this help message"
       echo "-P    ask for wallet passphrase"
       echo "-p    use provided passphrase (less secure, but useful in scripting)"
       echo "-l    addressbook label for new address"
       echo "-k    the private key for the new address (required)"
       echo ""
       echo "(c)2012 ElasticNinja bitcoin:1NinjaRFABUh48pwL5CdAYgnt8bTPnsuu4"
       exit 0;
}

while getopts "hk:l:p:P" option; do
  case $option in
   P)   askpass=1     ;;
   p)   pass=$OPTARG  ;;
   l)   label=$OPTARG ;;
   k)   key=$OPTARG   ;;
   *)   usage         ;;
  esac
done

if ((askpass==1)); then
   echo -n "Enter wallet passphrase: "
   stty -echo echonl
   read pass
   stty echo
fi

if [ -z "$key" ]; then
   echo "No private key specified!"
   exit 1
fi

if [ ! -z "$pass" ]; then
   unlock_wallet "$pass" 120 || fatal "Could not unlock wallet, passphrase incorrect?"
fi

echo "Importing key.. be patient, this may take a while."
import_key "$key" "$label" || fatal "Could not add key, wallet still locked?"

echo "All done!"
