#!/bin/bash

# ==========================================
# Initial Setup Script for Empty Server Folder
# ==========================================

# Print every command and fail on errors
set -e

# Configuration
APP_DIR="/var/www/html/glidecore"
REPO_URL="https://github.com/Digital-Glide/glidecore.git"
BRANCH="main"

echo "Starting initial setup at $(date)..."

# Ensure the directory exists
sudo mkdir -p "$APP_DIR"

# Ensure your current user has permissions to write to it temporarily (if created by sudo)
sudo chown -R $USER:$USER "$APP_DIR"

# Navigate to the application directory
cd "$APP_DIR" || exit 1

# Check if the directory is actually empty
if [ "$(ls -A "$APP_DIR")" ]; then
    echo "Error: Directory $APP_DIR is not empty. This script is intended for empty directories only."
    echo "If you already have code there, use the deployment script instead."
    exit 1
fi

echo "Directory is empty. Proceeding with initial clone..."

# Clone the repository directly into the current directory (the dot at the end is important)
# NOTE: Make sure your server has permissions to read from this repository
git clone "$REPO_URL" .

# Ensure we are on the correct branch
git checkout "$BRANCH"

# Optional: Set appropriate web server permissions after cloning
# echo "Setting standard web folder permissions..."
# sudo chown -R www-data:www-data "$APP_DIR"
# sudo find "$APP_DIR" -type d -exec chmod 755 {} \;
# sudo find "$APP_DIR" -type f -exec chmod 644 {} \;

echo "Initial setup completed successfully at $(date)."
