#!/bin/bash
set -e

# Mount S3 bucket if S3_BUCKET is provided
if [ -n "$S3_BUCKET" ]; then
  echo "Mounting S3 bucket $S3_BUCKET to /s3"
  
  # Build the base mount command
  MOUNT_COMMAND="/usr/local/bin/mounthelper -bucket $S3_BUCKET \
    -metadata-ttl ${METADATA_TTL:-60} \
    -allow-delete ${ALLOW_DELETE:-false} \
    -read-only ${READ_ONLY:-false}"
  
  # Add prefix if specified
  if [ -n "$S3_PREFIX" ]; then
    MOUNT_COMMAND="$MOUNT_COMMAND -prefix \"$S3_PREFIX\""
  fi
  
  # Prepare arguments list
  ARGS=""
  
  # Add local cache if specified
  if [ -n "$S3_CACHE_DIR" ]; then
    echo "Using local cache directory: $S3_CACHE_DIR"
    mkdir -p "$S3_CACHE_DIR"
    if [ -n "$ARGS" ]; then
      ARGS="$ARGS,--cache=$S3_CACHE_DIR"
    else
      ARGS="--cache=$S3_CACHE_DIR"
    fi
  fi
  
  # Add shared cache if specified
  if [ -n "$S3_CACHE_XZ_BUCKET" ]; then
    echo "Using shared cache bucket: $S3_CACHE_XZ_BUCKET"
    if [ -n "$ARGS" ]; then
      ARGS="$ARGS,--cache-xz=$S3_CACHE_XZ_BUCKET"
    else
      ARGS="--cache-xz=$S3_CACHE_XZ_BUCKET"
    fi
  fi
  
  # Add any additional mount args
  if [ -n "$MOUNT_ARGS" ]; then
    if [ -n "$ARGS" ]; then
      ARGS="$ARGS,$MOUNT_ARGS"
    else
      ARGS="$MOUNT_ARGS"
    fi
  fi
  
  # Add arguments to command if any were specified
  if [ -n "$ARGS" ]; then
    MOUNT_COMMAND="$MOUNT_COMMAND -args \"$ARGS\""
  fi
  
  # Execute the mount command
  echo "Running mount command: $MOUNT_COMMAND"
  eval $MOUNT_COMMAND &
  
  # Wait a moment for the mount to complete
  sleep 2
  
  # Verify the mount worked
  if [ ! -d "/s3" ] || [ -z "$(ls -A /s3 2>/dev/null)" ]; then
    echo "Warning: S3 mount may not be functioning correctly"
  else
    echo "S3 bucket successfully mounted at /s3"
  fi
fi

# Execute the original command
exec "$@"