#!/bin/bash

##
## BitDeals Module configuration helper script for Docker Container.
## It writes an Environment variables to the daemon config files.
## And can generate a Bitcoin and PGP key filies at first start.
##

DM_LC_ALL=${DM_LC_ALL:-"en_US.UTF-8"}
DM_TZ=${DM_TZ:-"Etc/UTC"}

export DM_FORWEB=${DM_FORWEB:-http://127.0.0.1}
export DM_TESTNET=${DM_TESTNET:-false}
export DM_WEB_LANG=${DM_WEB_LANG:-en}
export YEAR=$(date '+%Y')

## Variable for tput color output
export TERM=xterm

set_locale()
{
  ## Setup locale
  if [ "$DM_LC_ALL" ]; then
    update-locale LC_ALL="$DM_LC_ALL" LANG="$DM_LC_ALL"
  fi

  ## Setup Timezone
  if [ "$DM_TZ" ]; then
    echo $DM_TZ > /etc/timezone
    ln -snf /usr/share/zoneinfo/$DM_TZ /etc/localtime
    dpkg-reconfigure -f noninteractive tzdata
  fi
}

init_config()
{
  BITCOIN_KEYS_BACKUP="$UHOME/bitcoin.backup_and_remove"
  NPROC="$(nproc)"
  export WORKERS="${WORKERS:-$NPROC}"
  export PGP_SEC_FILE="$UHOME/pgp-key.sec"
  export DM_PRIVATEDASH="${DM_PRIVATEDASH:-false}"
  export DM_PRIVACY_MODE="${DM_PRIVACY_MODE:-false}"

  if [ "$DM_TESTNET" = false ]
  then
    export DM_OAUTH_WEB_SECRET="${DM_OAUTH_WEB_SECRET:-vTcvnpHbTmxxGP8AfRTHETXG}"
    export DM_OAUTH_MODULE_SECRET="${DM_OAUTH_MODULE_SECRET:-6DbqdnrJEDeSmaBMuZZde9ec}"
    export BITDEALS_PGP_FILE="/etc/dm/bitdeals.asc"
    export BITDEALS_SERVER=mainnet.bitdeals.org
    export BX_CONFIG="--config /usr/local/etc/libbitcoin/bx.cfg"
  else
    export DM_OAUTH_WEB_SECRET="${DM_OAUTH_WEB_SECRET:-4aJEJi3dsSypeUSRCah4gIIs}"
    export DM_OAUTH_MODULE_SECRET="${DM_OAUTH_MODULE_SECRET:-TypQHP4TK44khO3cvOyuHYg3}"
    export BITDEALS_PGP_FILE="/etc/dm/bitdeals-testnet.asc"
    export BITDEALS_SERVER=testnet.bitdeals.org
    export BX_CONFIG="--config /usr/local/etc/libbitcoin/bx-testnet.cfg"
  fi

  # User PGP secret key
  if [ "$DM_PGP_SEC" ]; then
    echo "$DM_PGP_SEC" > "$PGP_SEC_FILE"
  fi

  # BitDeals PGP public key
  if [ "$DM_BITDEALS_PGP" ]; then
    echo "$DM_BITDEALS_PGP" > "$BITDEALS_PGP_FILE"
  fi

  if [ "$DM_BITDEALS_PGP_FINGERPRINT" ]; then
    for i in {1..3}; do gpg --keyserver keyserver.ubuntu.com --recv-keys "$BITDEALS_KEY_FINGERPRINT" && break; done && \
    gpg --armor --export "$BITDEALS_KEY_FINGERPRINT" > "$BITDEALS_PGP_FILE"
    gpgconf --kill all
  fi

  # Create log directory
  install --directory --mode=755 --owner=$UNAME --group=$UNAME /var/log/dm

  envsubst < /opt/dm.conf > /etc/dm/dm.conf
  envsubst < /opt/conf/bitcoin.conf > /etc/dm/conf/bitcoin.conf
  envsubst < /opt/oauth2/default.json > /etc/dm/oauth2/default.json
  envsubst < /opt/oauth2/service.json > /etc/dm/oauth2/service.json
  envsubst < /opt/sites/default.json > /etc/dm/sites/default.json
  envsubst < /opt/config.js > /var/www/app/config.js
}

generate_pgp_key()
{
  ## Create user PGP key if the file is empty
  if [ ! -f "$PGP_SEC_FILE" ]
  then
	  if [ ! "$DM_ACCOUNT_URL" ]
	  then
	          echo -en "Generating new PGP key...\nPlease enter your site URL like https://example.com : "
	          read DM_ACCOUNT_URL \
              || { echo -en "\n" ; DM_ACCOUNT_URL="https://example-$RANDOM$RANDOM.com" ;}
	  fi

    #GNUPGHOME="$(mktemp -d)" ; ## Works for gpg2
    gpg --faked-system-time $(TZ=UTC date --date=$(date +'%Y-%m-%d') +%s) \
      --pinentry-mode loopback --passphrase "$DM_PGP_PASSWORD" \
      --openpgp --batch --gen-key 2>/dev/null <<-EOF
    Key-Type: RSA
    Key-Usage: cert,sign
    Key-Length: 1024
    Subkey-Type: RSA
    Subkey-Usage: encr
    Subkey-Length: 1024
    Name-Real: Account_URL
    Name-Comment: http://$(basename $DM_ACCOUNT_URL)
    Expire-Date: 0
EOF

    #add "https://Account_URL" to key uid
    echo -e "Account_URL\n\nhttps://$(basename $DM_ACCOUNT_URL)\nO\nsave\n" | \
      gpg --passphrase "$DM_PGP_PASSWORD" --command-fd 0 --edit-key Account_URL adduid

    tput setaf 2
    cat <<-EOF

    $(gpg -k --keyid-format long 2>/dev/null | tail -n5)
    $(echo ; gpg --armor --export-secret-keys --passphrase "$DM_PGP_PASSWORD" | tee "$PGP_SEC_FILE")
EOF
    tput sgr0
    gpgconf --kill all
  else
    echo -e "NOTE: Your PGP key location: $PGP_SEC_FILE"
  fi

  ## Change PGP keyfile owner
  if [ -f "$PGP_SEC_FILE" ]; then
         chown $UNAME:$UNAME "$PGP_SEC_FILE"
         chmod 600 "$PGP_SEC_FILE"
  fi
}

generate_btc_key()
{
  ## Create new Bitcoin keys. If user address (_DM_BITCOIN var) is empty.
  _DM_BITCOIN="$(sed -n '/^[ \t]*\[module\]/,/\[/s/^[ \t]*address[ \t]*=[ \t]*//p' /etc/dm/dm.conf)"

  B=$(tput bold ; tput setaf 1)
  N=$(tput sgr0)

  if [ -z "$_DM_BITCOIN" -a -z "$DM_BITCOIN" ]
  then
    ## Generate bitcoin key pair
    PRIVKEY="$(cat /dev/random | tr -cd "[:digit:]" | head -c 64)"
    PUBKEY="$(/usr/local/bin/bx ec-to-public $PRIVKEY $BX_CONFIG)"
    BITCOIN="$(/usr/local/bin/bx ec-to-address $PUBKEY $BX_CONFIG)"
    PRIVKEYWIF="$(/usr/local/bin/bx ec-to-wif $PRIVKEY $BX_CONFIG)"

    ## Write the bitcoin address to the daemon config
    sed -i "/\[module\]/,/\[/ s/^#*address=.*/address=$BITCOIN/" /etc/dm/dm.conf

    ## Show bitcoin key
    tee -a $BITCOIN_KEYS_BACKUP <<-EOF

${B}Please backup this 	BITCOIN KEY:${N}
Private key (WIF form):	$PRIVKEYWIF
Public key:		$PUBKEY
Bitcoin address:    	$BITCOIN

EOF
    chmod 600 $BITCOIN_KEYS_BACKUP
  else
    test -f $BITCOIN_KEYS_BACKUP \
    && echo -e "NOTE: Your Bitcoin key saved to $(dirname $BITCOIN_KEYS_BACKUP)/${B}$(basename $BITCOIN_KEYS_BACKUP)${N}"\
    || echo -e "NOTE: Your Bitcoin address: $_DM_BITCOIN\n"
  fi
}


set_locale
init_config
generate_pgp_key
generate_btc_key


## Run the daemon
/etc/init.d/nginx start
exec /usr/sbin/dm -p /etc/dm -c /etc/dm/dm.conf $@

