#!/bin/bash

chmod 600 "/abs/zabbix/externaltools/zbxdb/bin/.keyfile"
chmod 600 "/abs/zabbix/externaltools/zbxdb/bin/ftp_password.enc"

export HOME="/abs/zabbix/externaltools/zbxdb"
export FTP_SERVER="ftp.abssolute.net"
export FTP_USER="ABS_SLA_REP"
export SCRIPT_DIR="$HOME/bin"
export ENCRYPTED_PASS_FILE="$SCRIPT_DIR/ftp_password.enc"
export KEY_FILE="$SCRIPT_DIR/.keyfile"
export REMOTE_DIRECTORY="/zbxdb_checks"
export LOCAL_DIRECTORY="$HOME/etc/zbxdb_checks/oracle"
export LOG_FILE="$SCRIPT_DIR/download.log"

# Ensure encryption files exist
if [[ ! -f "$ENCRYPTED_PASS_FILE" || ! -f "$KEY_FILE" ]]; then
  echo "❌ Missing encryption files. Expected:"
  echo "  - $ENCRYPTED_PASS_FILE"
  echo "  - $KEY_FILE"
  exit 1
fi

# Decrypt the password
FTP_PASSWORD=$(openssl enc -aes-256-cbc -d -pbkdf2 -in "$ENCRYPTED_PASS_FILE" -pass file:"$KEY_FILE")

# Ensure local dir exists
mkdir -p "$LOCAL_DIRECTORY"

echo "⬇️  Syncing newer .cfg files from $FTP_SERVER..."

# Run lftp and capture output
LFTP_OUTPUT=$(lftp -u "$FTP_USER","$FTP_PASSWORD" sftp://$FTP_SERVER:50022 <<EOF
set sftp:auto-confirm yes
set ssl:verify-certificate no
set cmd:fail-exit no

cd $REMOTE_DIRECTORY
lcd $LOCAL_DIRECTORY

mirror \
    --only-newer \
    --include-glob=*.cfg \
    --verbose \
    --parallel=2 \
    .

bye
EOF
)

# Extract transferred files
COPIED_FILES=$(echo "$LFTP_OUTPUT" | grep -E "Transferring|get:")

echo "$LFTP_OUTPUT"  # optional full output

echo "✅ Sync finished."

if [[ -z "$COPIED_FILES" ]]; then
  echo "ℹ️  No new .cfg files were copied."
else
  echo "📄 Files copied:"
  echo "$COPIED_FILES"
fi
