#!/usr/bin/env bash
# Desc: Wrapper for ots-git-gpg-wrapper
# Note: Required because git's gpg.program option doesn't allow you to set
#   command line options.
# Usage: git -c gpg.program=<path to ots-git-gpg-wrapper.sh> commit -S
# Input: file: $HOME/.local/share/ots/jsonrpc_url.txt  # first line is JSON RPC
#          url for local bitcoin node containing login credentials. Example:
#            http://user:35z8deadbeefhrdeadbeef5rk3@192.168.86.1:8332/
# Depends: ots 0.7.0 (see https://github.com/opentimestamps/opentimestamps-client )
# Version: 0.0.6
# Ref/Attrib: [1] “How can I test if a particular alias is defined?”. https://unix.stackexchange.com/a/288513
#             [2] “OpenTimestamps Git Integration”. (2016-10-13). https://github.com/opentimestamps/opentimestamps-client/blob/master/doc/git-integration.md

declare -a args calendars

# Specify default calendars
calendars+=("https://finney.calendar.eternitywall.com");
calendars+=("https://btc.calendar.catallaxy.com");
calendars+=("https://alice.btc.calendar.opentimestamps.org");
calendars+=("https://bob.btc.calendar.opentimestamps.org");

# Check if gpg is alias. See [1].
if alias gpg 2>/dev/null; then
    ## Get gpg alias command
    gpg_cmd="$(type gpg)"; # get raw alias definition
    gpg_cmd="${gpg_cmd#*=\'}"; # trim chars before and including first apostrophe
    gpg_cmd="${gpg_cmd%\'*}"; # trim chars after and including last apostrophe
else
    gpg_cmd="$(which gpg)";
fi;

# Assemble args array
## Specify bitcoin node jsonrpc url if available
path_jsonrpc_url="$HOME/.local/share/ots/jsonrpc_url.txt";
if [[ -f "$path_jsonrpc_url" ]]; then
    jsonrpc_url="$(head -n1 "$path_jsonrpc_url")";
    args+=("--bitcoin-node");
    args+=("$jsonrpc_url");
fi;

## Pick random calendar
### Get calendars array size
cal_size="${#calendars[@]}";
cal_rnd_idx="$(shuf -i 1-"$cal_size" -n 1)";
cal_rnd_idx="$((cal_rnd_idx - 1))"; # bash array is zero-indexed
url_cal_random="${calendars[$cal_rnd_idx]}";
args+=("--no-default-whitelist");
args+=("--whitelist");
args+=("$url_cal_random");

## Specify '--gpg-program' option
args+=("--gpg-program");
args+=("$gpg_cmd");

## Passthrough positional parameters
args+=("--"); # mark end of ots-git-wrapper options
for param in "$@"; do
    args+=("$param");
done;

# Run command with args
#   pseudocode: ots-git-gpg-wrapper $jsonrpc_option $calendar_option --gpg-program $gpg_cmd -- "$@"
ots-git-gpg-wrapper "${args[@]}";
