#!/bin/bash

# Physio-Remotion Deployment Script
# This script loads credentials from .env and deploys the 'dist' folder via SFTP.

# Load .env file
if [ -f .env ]; then
    export $(cat .env | xargs)
else
    echo "Error: .env file not found."
    exit 1
fi

# Check for required variables
REQUIRED_VARS=("SFTP_USER" "SFTP_PASS" "SFTP_HOST" "SFTP_PORT" "SFTP_SUB_DIR")
for VAR in "${REQUIRED_VARS[@]}"; do
    if [ -z "${!VAR}" ]; then
        echo "Error: $VAR is not set in .env"
        exit 1
    fi
done

echo "--- Starting Build ---"
npm run build

if [ $? -ne 0 ]; then
    echo "Build failed. Aborting deployment."
    exit 1
fi

echo "--- Starting Deployment to $SFTP_HOST ---"

# We use lftp for robust directory mirroring with password support.
# If lftp is not installed, it can be installed via 'brew install lftp' on macOS.
if ! command -v lftp &> /dev/null; then
    echo "Error: lftp is not installed. Please install it using 'brew install lftp'."
    exit 1
fi

lftp -u "$SFTP_USER","$SFTP_PASS" -p "$SFTP_PORT" sftp://"$SFTP_HOST" <<EOF
set sftp:auto-confirm yes
set net:timeout 10
set net:max-retries 2
mkdir -p $SFTP_SUB_DIR
cd $SFTP_SUB_DIR
mirror -R dist/ .
quit
EOF

if [ $? -eq 0 ]; then
    echo "--- Deployment Successful! ---"
else
    echo "--- Deployment Failed. ---"
    exit 1
fi
