#!/bin/sh

#
# Copyright (C) 2022 Nethesis S.r.l.
# SPDX-License-Identifier: GPL-2.0-only
#

#
# Manage remote backup
#

function exit_error {
    >&2 echo "[ERROR] $@"
    exit 1
}

function help {
    >&2 echo "Usage: $0 <list|download|upload>"
    >&2 echo "Commands:"
    >&2 echo " - list: retrieve the list of available backups from remote server"
    >&2 echo " - download <file> [output]: download the given backup, if 'output' is empty downloaded file will be named as as 'file'"
    >&2 echo " - upload <file>: upload the given backup"
}

SYSTEM_ID=$(uci -q get ns-plug.config.system_id)
SYSTEM_SECRET=$(uci -q get ns-plug.config.secret)
TYPE=$(uci -q get ns-plug.config.type)
URL=$(uci -q get ns-plug.config.backup_url)

if [ -z "$SYSTEM_ID" ] || [ -z "$SYSTEM_SECRET" ] || [ -z "$URL" ]; then
    exit_error "System ID, system secret or backup url not found. Please configure ns-plug."
fi

curl_args="--silent --location-trusted --user $SYSTEM_ID:$SYSTEM_SECRET"
base_url="$URL/$TYPE/api/v2/backup/"

cmd=${1:-list}

case "$cmd" in
    list)
        curl $curl_args $base_url
        ;;
    download)
        file=$2
        if [ -z "$file" ]; then
           exit_error "No file specified"
        fi
        output=${3-$file}
        curl $curl_args $base_url$file -J -o "$output"
       ;;
   upload)
       file=$2
       if [ -z "$file" ]; then
           exit_error "No file specified"
       fi
       curl $curl_args $base_url --upload-file $file
       rc=$?
       # Temporary dual-send to new my.nethesis.it via the translation
       # proxy, same pattern used by send-heartbeat / send-inventory.
       # To be removed once the migration is complete.
       if [ "$TYPE" = "enterprise" ]; then
           # Strip the directory path first to get just the filename
           filename="${file##*/}"
           curl $curl_args -X POST \
               -H "Content-Type: application/octet-stream" \
	       -H "X-Filename: ${filename}" \
               --data-binary "@$file" https://my.nethesis.it/proxy/backup >/dev/null || :
       fi
       exit $rc
       ;;
   delete)
       file=$2
       if [ -z "$file" ]; then
           exit_error "No file specified"
       fi
       curl $curl_args -X DELETE $base_url$file
       ;;

   *)
       help
      ;;
esac
