#!/usr/bin/env bash
#
# Keyringer key management system.
#
# Copyright (C) 2010 Silvio Rhatto - rhatto at riseup.net
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License,
# or any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# Initialize a new keyring
function keyringer_init {
  BASEDIR="$3"
  URL="$4"
  RECIPIENTS="$BASEDIR/config/recipients"
  OPTIONS="$BASEDIR/config/options"
  VERSION_INFO="$BASEDIR/config/version"

  # We are initializing, so avoid some checks
  export KEYRINGER_CHECK_VERSION="false"
  export KEYRINGER_CHECK_RECIPIENTS="false"

  # Parse
  if [ -z "$BASEDIR" ]; then
    echo "Usage: $BASENAME <keyring> init <path> [url]"
    exit 1
  elif grep -q -e "^$KEYRING=" $CONFIG; then
    echo "Keyring $KEYRING already defined"
    exit 1
  fi

  # Check user configuration: git might complain if those aren't set
  if [ -z "`git config --global --includes --get user.name`" ] || [ -z "`git config --global --includes --get user.email`" ]; then
    echo "No git config found, so please chose a name and email address to identify your changes in the new keyring repository."
    read -p "Enter your desired name/pseudonym: " name
    read -p "Enter your desired email address: " email

    if [ -z "$name" ] || [ -z "$email" ]; then
      echo "Aborting."
      exit 1
    fi
  fi

  # Setup
  if [ ! -z "$URL" ]; then
    git clone "$URL" "$BASEDIR"
    if [ "$?" != "0" ]; then
      echo "Error cloning remote $URL"
      exit 1
    fi
  else
    if [ -e "$BASEDIR" ]; then
      if [ ! -d "$BASEDIR/keys" ] || [ ! -e "$RECIPIENTS" ]; then
        echo "Invalid keyring $BASEDIR: incomplete installation"

        # A common mistake
        if [ -d "$BASEDIR/../keys" ]; then
          echo "You might try `cd $BASEDIR/.. && pwd` instead"
        fi

        exit 1
      fi
    else
      # Setup folders
      mkdir -p "$BASEDIR/"{config,keys}

      # Setup recipients
      keyringer_create_new_recipients "$RECIPIENTS/default"

      # Setup options
      touch "$OPTIONS"

      # Setup README
      echo "Keyring repository powered by https://keyringer.fluxo.info" > "$BASEDIR/README"
      echo "" >> "$BASEDIR/README"

      # Set config version
      echo $CONFIG_VERSION > $VERSION_INFO
    fi

    # Secure
    chmod 700 "$RECIPIENTS"
  fi

  # Reparse basedir to force absolute folder
  BASEDIR="`cd $BASEDIR &> /dev/null && pwd`"

  # Add entry
  chmod 700 "$BASEDIR"
  echo "$KEYRING=\"$BASEDIR\"" >> "$CONFIG"
  touch $CONFIG_BASE/$KEYRING

  # Init
  if ! keyringer_is_git "$BASEDIR"; then
    keyringer_exec git "$BASEDIR" init
    keyringer_git_ignore 'tmp/*'

    # Git configuration
    if [ ! -z "$email" ]; then
      git config user.email "$email"
      git config user.name  "$name"
    fi

    # Edit default recipients
    if [ "$KEYRINGER_NON_INTERACTIVE" != "1" ]; then
      echo "Now you have to edit the default recipient configuration to be able to encrypt secrets."
      echo "Press any key to proceed editing..."
      read key
      keyringer_exec recipients "$BASEDIR" edit default
    fi

    # Stage and commit
    keyringer_exec git "$BASEDIR" add .
    keyringer_exec git "$BASEDIR" commit -m Initializing
  fi
}

# Action dispatcher
function keyringer_dispatch {
  BASEDIR="`keyringer_config $KEYRING`"

  # Dispatch
  if [ ! -z "$BASEDIR" ]; then
    shift 2
    keyringer_exec "$ACTION" "$BASEDIR" $*
    exit $?
  else
    echo "No keydir configured for $KEYRING"
    exit 1
  fi
}

# Config
NAME="keyringer"
KEYRINGER_VERSION="0.7.2"
CONFIG_VERSION="0.1"
CONFIG_BASE="$HOME/.$NAME"
CONFIG="$CONFIG_BASE/config"
BASENAME="`basename $0`"
KEYRING="$1"
ACTION="$2"

# Turn off pathname expansion so expansion can work properly
set -f

# Set functions location
if [ -e "`dirname $(readlink -f $0)`/lib/$NAME/functions" ]; then
  # Development or local installation layout
  LIB="`dirname $(readlink -f $0)`/lib/$NAME/functions"
else
  # System installation layout
  LIB="`dirname $(readlink -f $0)`/../lib/$NAME/functions"
fi

# Set shared files location
if [ -e "`dirname $(readlink -f $0)`/share/$NAME" ]; then
  # Development or local installation layout
  SHARE="`dirname $(readlink -f $0)`/share/$NAME"
else
  # System installation layout
  SHARE="`dirname $(readlink -f $0)`/../share/$NAME"
fi

# Set actions location
if [ -e "`dirname $(readlink -f $0)`/lib/$NAME/actions" ]; then
  # Development or local installation layout
  ACTIONS="`dirname $(readlink -f $0)`/lib/$NAME/actions"
else
  # System installation layout
  ACTIONS="`dirname $(readlink -f $0)`/../lib/$NAME/actions"
fi

# Export globals for other scripts
export PREFERENCES="`dirname $CONFIG`/$KEYRING"
export KEYRINGER_VERSION
export CONFIG_VERSION
export KEYRING
export CONFIG
export SHARE

# Load functions
source "$LIB" || exit 1

# Basic checks
if [ -z "$KEYRING" ]; then
  keyringer_usage
  exit 1
elif [ ! -f "$CONFIG_BASE/$KEYRING" ] && [ "$ACTION" != "init" ]; then
  echo "No such keyring $KEYRING"
  exit 1
fi

# Setup main configuration and load preferences
keyringer_config_load

# Dispatch
if [ -z "$ACTION" ]; then
  # Run shell if no action were given
  keyringer $KEYRING shell
elif [ "$ACTION" == "init" ]; then
  keyringer_init $*
elif keyringer_has_action "$ACTION"; then
  keyringer_dispatch $*
else
  echo "No such action $ACTION"
  exit 1
fi
