#!/bin/bash
# ************************************************
# Copyright (c) 2020 FXDaemon All Rights Reserved.
# ************************************************

cur_dir=$(cd $(dirname $0);pwd)

if [ $# -eq 1 ]; then
  install_pkg=$1
else
  echo Please specify an installation package.
  echo Usage: setup.sh PACKAGE-NAME
  exit 1
fi
if [ ! -e $install_pkg ]; then
  echo $install_pkg does not exist in the current directory.
  exit 1
fi

which mysql > /dev/null 2>&1
if [ $? -eq 1 ]; then
  echo "Please add mysql into PATH."
  exit 1
fi

echo -n "Please specify the installation directory, or press <Enter> to select the home directory: "
read out_dir
if [ -z $out_dir ]; then
  out_dir=~
fi
if [ ! -e $out_dir ]; then
  echo Installation directory does not exist.
  exit 1
fi
echo $out_dir

echo "Extract the installation package."

install_dir=$out_dir/fxtrade
if [ -e $install_dir ]; then
  echo -n "The installation directory already exists, overwrite it(y/n)?"
  read yes_no
  if [ "$yes_no" != "y" ]; then
    echo Installation aborted.
    exit 1
  fi
fi

cd $out_dir && tar xzvf $cur_dir/$install_pkg --no-same-owner
if [ $? -eq 1 ]; then
  exit 1
fi

cd fxtrade
cat SETENV | sed "s#REPL_PATH#$install_dir/bin#g" > setenv.sh
chmod +x setenv.sh fxTrade.sh
rm -f SETENV
cd bin
tar xvf fxtrade-lib.tar
rm -f fxtrade-lib.tar

echo -n "Create a new database <scm_fxtrade>, continue(y/n)? Press <Enter> for yes: "
read yes_no
if [ -z "$yes_no" ]; then
  yes_no=y
fi
if [ "$yes_no" != "y" ]; then
  echo Installation aborted.
  exit 1
fi

echo -n "Please specify the database user, or press <Enter> to select the root user: "
read db_usr
if [ -z $db_usr ]; then
  db_usr=root
fi

mysql -u$db_usr -p < $install_dir/sql/fxtrade.sql
if [ $? -eq 1 ]; then
  sudo mysql -u$db_usr -p < $install_dir/sql/fxtrade.sql
  if [ $? -eq 1 ]; then
    echo "Failed to create database."
    exit 1
  fi
fi

echo "Setup is complete!"
