#!/bin/bash
#
# Welcom to use Bigemap Server
# Copyright(c) 2020 BIGEMAP
#

help_download() {
  echo -e "
The download command downloads all the files necessary to install Bigemap Server.

Usage:

  ./bm-server-installer download <destination> [options]

  <destination>   : (required) The directory where the downloaded files will be saved. 
                    Must be on the same computer as the installer.

Options:

  --version       : (optional) to download Bigemap Server version. 
                    By default, the download command will download the latest release.
                    You can use the list command to see the list of Bigemap server
                    versions that are available to download.

Example:

  ./bm-server-installer download bm-server-files/
"
}

download() {
  if [ ! -n "$1" ]; then
    echo -e "You must specify the directory. \n"
    help_download
    exit 1
  fi

  DESTINATION="$1"

  if [ -n "$2" ]; then
    case $2 in
    "--version")
      shift
      DOWN_VERSION="$2"
      shift
      ;;
    *)
      echo "Error option $2"
      help_download
      exit 1
      ;;
    esac
  fi

  mkdir -p "$DESTINATION/docker" || exit 1

  if [ ! -n "$DOWN_VERSION" ]; then
    DOWN_VERSION=$(wget -q -O - $SERVER_URL/bm-server/$PLATFORM/versions | sort -V |tail -n 1)
    if [[ $? -ne 0 || ! -n $DOWN_VERSION ]]; then
      echo "Get latest version failed!"
      exit 1
    fi
    echo "Get the newest version $DOWN_VERSION"
  fi

  DFILE="bm-server-$DOWN_VERSION-$BM_ARCH.tar.gz"

  echo "Downloading docker files ..."
  wget -c $SERVER_URL/bm-server/$PLATFORM/$DFILE -O $DESTINATION/docker/$DFILE

  if [ $? -ne 0 ]; then
    echo -e "${RED}Download failed!${NC}"
    exit 1
  fi

  echo -e "${GREEN}Bigemap Server downloads completed.${NC}"
  return 0
}