#!/bin/bash

#
# The kylinfs_init script deploy kylinfs with the user configuration kfs.json.

INSTALL_DIR="/opt/kylinfs"
CFG="$INSTALL_DIR/kfs.json"

function usage
{
  cat << EOF
Usage:
    Initialize kylinfs using the configuration in $CFG
        `basename $0` -u user -p password_of_user
        `basename $0` -u user -n
        `basename $0` -u user -p password_of_user -v
Options:
    -u  user name to deploy kylinfs
    -p  password of user on all kylinfs nodes
    -v  use $CFG to verify the kylinfs installation environment
    -n  do not execute the mutual trust script
    -q  non-interactive mode
    -h  help
EOF
  exit 1
}

function do_mutual_trust
{
  nodes=$(grep '"ip":' $CFG|awk -F: '{print $2}'|tr -d ',"' |tr -s "\n" " "| sed 's/ $//g')
  sudo $INSTALL_DIR/mutual-trust -u $duser -p $dpasswd -l "$nodes"
  if [ $? -ne 0 ] ;then
    echo "Failed to do mutual_trust for $nodes"
    exit 1
  fi
}


function deploy_kylinfs
{
  cd $INSTALL_DIR
  if [ $quiet == true ]; then
    sudo python3 main.py -c $CFG -m install -u $USER -q
  else
    sudo python3 main.py -c $CFG -m install -u $USER
  fi
}

function validate_env
{
  cd $INSTALL_DIR
  sudo python3 main.py -c $CFG -m validate -u $USER
}

no_mutual_trust=false
validate=false
quiet=false
duser=""
dpasswd=""
while getopts "hu:p:nvq" options
do
    case $options in
        n)
          no_mutual_trust=true;;
        v)
          validate=true;;
        u)
          duser="$OPTARG";;
        p)
          dpasswd="$OPTARG";;
        q)
          quiet=true;;
        h)
          usage
          ;;
        *)
          usage
          ;;
    esac
done

if [ ! -f $CFG ]; then
  CFG="./kfs.json"
fi

if [ $no_mutual_trust == false ]; then
  if [ -z $duser ] && [ -z $dpasswd ]; then
    echo "please set the username and password to do ssh connection for kylinfs nodes"
    exit 1
  fi
  do_mutual_trust
fi

if [ $validate == true ]; then
  validate_env
  exit 0
fi

deploy_kylinfs
