#!/bin/bash

# Exit on errors
set -e

# Configuration (environment variables)
BUILD_DIR=".tmp_build" # Temporary directory for the build
PRODUCTION_SERVER="${PRODUCTION_SERVER:-}" # Ensure this is set in the environment
PRODUCTION_PATH="${PRODUCTION_PATH:-}"    # Ensure this is set in the environment
PATH_PREFIX="${PATH_PREFIX:-}"  # Ensure this is set in the environment
SITE_URL="${SITE_URL:-}"                  # Ensure this is set in the environment
CDN_URL="${CDN_URL:-}"                    # Ensure this is set in the environment
FOUNDRY_BASE_URL="${FOUNDRY_BASE_URL:-}"  # Ensure this is set in the environment

# Function to clean up the temporary directory
cleanup() {
  echo "Cleaning up temporary files..."
  rm -rf "$BUILD_DIR"
}

# Set trap to clean up on script exit or interruption
trap cleanup EXIT

# Function to check environment variables
check_env() {
  if [[ -z "$PRODUCTION_SERVER" ]]; then
    echo "Error: PRODUCTION_SERVER is not set. Please set it and try again."
    exit 1
  fi

  if [[ -z "$PRODUCTION_PATH" ]]; then
    echo "Error: PRODUCTION_PATH is not set. Please set it and try again."
    exit 1
  fi

  if [[ -z "$PATH_PREFIX" ]]; then
    echo "Error: PATH_PREFIX is not set. Please set it and try again."
    exit 1
  fi

  if [[ -z "$SITE_URL" ]]; then
    echo "Error: SITE_URL is not set. Please set it and try again."
    exit 1
  fi

  if [[ -z "$CDN_URL" ]]; then
    echo "Error: CDN_URL is not set. Please set it and try again."
    exit 1
  fi

  if [[ -z "$FOUNDRY_BASE_URL" ]]; then
    echo "Error: FOUNDRY_BASE_URL is not set. Please set it and try again."
    exit 1
  fi
}

# Check environment variables
check_env

# Step 1: Build the site to a temporary directory
echo "Building the site..."
npx @11ty/eleventy --output="$BUILD_DIR"

# Step 2: Deploy using rsync
echo "Deploying to production..."
rsync -avz --delete "$BUILD_DIR/" "$PRODUCTION_SERVER:$PRODUCTION_PATH"

# Step 3: Fix permissions on the remote server
echo "Fixing permissions on the server..."
ssh "$PRODUCTION_SERVER" << EOF
  find "$PRODUCTION_PATH" -type f -exec chmod 665 {} \; # Set permissions for files
  find "$PRODUCTION_PATH" -type d -exec chmod 775 {} \; # Set permissions for directories
EOF

echo "Deployment complete!"