#!/bin/sh
#
# linbo_download
# thomas@linuxmuster.net
# 20250423
#

usage(){
  local RC="$1"
  echo
  echo "Downloads a file or a directory from the server into the current directory."
  echo
  echo "Usage: linbo_download [server ip] <file|dir> [important] | [help]"
  echo
  echo "Note:"
  echo "* \"server ip\" is depreMcated and can be ommitted."
  echo "* \"important\" increases verbosity."
  echo "* Use a trailing slash with \"dir\" to download a directory recursively."
  echo
  exit "$RC"
}

# print help
[ -z "$1" -o "$1" = "help" ] && usage 0

# get environment
source /usr/share/linbo/shell_functions
echo "### $timestamp $(basename "$0") $@ ###"

# do not execute in localmode
if localmode; then
  echo "Local mode detected!"
  exit 0
fi

# check params
if validip "$1"; then shift; fi
FILE="$1"
IMPORTANT="$2"

[ -z "$FILE" ] && usage 1

# downloads files from server into current directory
RC=1
[ -n "$IMPORTANT" ] && echo "RSYNC Download $LINBOSERVER -> $FILE ..."
TARGET="$(basename $FILE)"
# ensure target dir exists
[ "${TARGET: -1}" = "/" ] && mkdir -p "$TARGET"
interruptible rsync --skip-compress="$RSYNC_SKIP_COMPRESS" -HaLz --partial --progress "$LINBOSERVER::linbo/$FILE" "$TARGET" &> /dev/null; RC="$?"
if [ "$RC" != "0" ]; then
  # Delete incomplete/defective/non-existent file (maybe we should check for returncode=23 first?)
  rm -f "$FILE"
  if [ -n "$IMPORTANT" ]; then
    # Verbose error message if file was important
    echo "File $FILE could not be downloaded."
  fi
fi
exit "$RC"
