#!/usr/bin/env bash
set -euo pipefail

export basedir=$(cd $(dirname $0); pwd)

export DOCKER_PKG=24.0.9.tar.gz
export FINCLIP_PKG=finclip-cloud-latest.tar.gz
export FINCLIP_PKG_URL=https://temp-1251849568.cos.ap-guangzhou.myqcloud.com/finclip-cloud-latest.tar.gz


Color_Off=''
Red=''
Green=''
Dim='' # White
Bold_White=''
Bold_Green=''

if [[ -t 1 ]]; then
    Color_Off='\033[0m' # Text Reset
    Red='\033[0;31m'   # Red
    Green='\033[0;32m' # Green
    Dim='\033[0;2m'    # White
    Bold_Green='\033[1;32m' # Bold Green
    Bold_White='\033[1m'    # Bold White
fi

error() {
    echo -e "${Red}error${Color_Off}:" "$@" >&2
    exit 1
}

info() {
    echo -ne "${Dim}$@ ${Color_Off}"
}

info_bold() {
    echo -e "${Bold_White}$@ ${Color_Off}"
}

success() {
    echo -e "${Green}$@ ${Color_Off}"
}

info "请输入您的 License:"
read FINCLIP_LICENSE
if [ -z "$FINCLIP_LICENSE" ]; then
  echo "License 错误，退出安装.";
  exit 0;
fi


info "设置访问端口，默认 (8000):"
read FINCLIP_PORT
export FINCLIP_PORT=${FINCLIP_PORT:-8000}

info "FinClip 安装目录( 更改目录或按<Enter> $basedir ):"
read FINCLIP_HOME
FINCLIP_HOME=${FINCLIP_HOME:-$basedir}
mkdir -p $FINCLIP_HOME

download() {
  local d=$1
  local s=$2

  if [ -z "$d" ] || [ -z "$s" ]; then
    return 1
  fi

  test -e $d && mv $d "$d"-`date +%Y-%m-%d`
  curl -sSL $s -o $d
  return $?
}

#check and download.
if [ -e "$FINCLIP_PKG" ]; then
  echo "文件已存在，直接离线安装。"
else
  info "文件不存在, 访问网络下载中...";echo
  download $FINCLIP_PKG $FINCLIP_PKG_URL || {
    error "文件下载失败";
    exit 1;
  }
fi

#pre_install

tar xf $FINCLIP_PKG -C $FINCLIP_HOME

cd $FINCLIP_HOME/finclip-cloud

#install_docker

command -v docker >/dev/null || {
    info 'docker is required to install FinClip';echo
    read -p "Do you want to install Docker? (y/n): " docker_answer

    case $docker_answer in
        [Yy]* )
            echo "You have chosen to install Docker."
            tar xf ${DOCKER_PKG}

            cd docker-24.0.9/
            bash install.bash || exit 1
	          cd -
            ;;
        [Nn]* )
            echo "You have chosen not to install Docker."
            exit 0
            ;;
        * )
            echo "Invalid input, Docker installation aborted."
            exit 1
            ;;
    esac
}

#check_docker_cps

export CPS=docker-compose
docker compose version  > /dev/null && export CPS="docker compose"

$CPS > /dev/null || {
    echo "docker-compose is required to install finclip"
    exit 1
}

#install
cd $FINCLIP_HOME/finclip-cloud
docker load -i images.tgz
sed -i  "s@LICENSE_ENCRYPTION_STR:.*@LICENSE_ENCRYPTION_STR: $FINCLIP_LICENSE@g" fc-private.yaml
sed -i  "s@\".*:8000\"@\"$FINCLIP_PORT:8000\"@g" docker-compose.yaml

bash init.bash
docker compose up -d mysql redis minio registry
sleep 15
docker compose up -d quark
sleep 5
docker compose up -d

success "FinClip 安装完成 🎉🎉 "
