#!/bin/bash

# Admin Laravel Project Setup Script
# Run this script from /var/www/laravel directory

set -e  # Exit on any error

# Project configuration
PROJECT_NAME="admin"
GIT_REPO="https://github.com/kritib/qslaravel.git"
PROJECT_DIR="/var/www/laravel/$PROJECT_NAME"
ENVIRONMENT=""
TARGET_BRANCH=""

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Function to setup environment
setup_environment() {
    print_status "Setting up deployment environment..."
    
    echo "Choose deployment environment:"
    echo "1. Development (uses development branch)"
    echo "2. Production (uses main/master branch)"
    read -p "Enter your choice (1-2): " -n 1 -r
    echo
    
    case $REPLY in
        1)
            ENVIRONMENT="development"
            TARGET_BRANCH="development"
            print_success "Selected Development environment"
            ;;
        2)
            ENVIRONMENT="production"
            TARGET_BRANCH="main"
            print_success "Selected Production environment"
            ;;
        *)
            print_error "Invalid choice. Exiting."
            exit 1
            ;;
    esac
}

# Function to clone repository with authentication
clone_repository() {
    print_status "Initializing empty Git repository..."

    # Create project directory
    sudo mkdir -p "$PROJECT_NAME"
    cd "$PROJECT_NAME"

    # Init empty repo
    sudo git init

    # Add remote
    sudo git remote add origin "$GIT_REPO"

    # Fetch remote branches
    sudo git fetch origin

    # Checkout the target branch
    print_status "Checking out branch: $TARGET_BRANCH"
    if sudo git checkout -b "$TARGET_BRANCH" origin/"$TARGET_BRANCH"; then
        print_success "Checked out $TARGET_BRANCH branch"
    else
        print_error "Failed to checkout branch: $TARGET_BRANCH"
        exit 1
    fi

    # Pull latest changes
    print_status "Pulling latest code from $TARGET_BRANCH..."
    if sudo git pull origin "$TARGET_BRANCH"; then
        print_success "Repository initialized successfully"
    else
        print_error "Failed to pull from origin/$TARGET_BRANCH"
        exit 1
    fi
}


# Function to check if required tools are installed
check_dependencies() {
    local missing_tools=()
    
    if ! command -v git &> /dev/null; then
        missing_tools+=("git")
    fi
    
    if ! command -v composer &> /dev/null; then
        missing_tools+=("composer")
    fi
    
    if ! command -v npm &> /dev/null; then
        missing_tools+=("npm")
    fi
    
    if ! command -v php &> /dev/null; then
        missing_tools+=("php")
    fi
    
    if [ ${#missing_tools[@]} -ne 0 ]; then
        print_error "Please install them first:"
        print_error "Missing required tools: ${missing_tools[*]}"
        return 1
    fi
    return 0
}

# Main setup function
main() {
    print_status "=== '$PROJECT_NAME' Laravel Project Setup ==="
    
    # Setup environment first
    setup_environment
    
    # Check current directory
    if [[ ! "$PWD" =~ /var/www/?$ ]] && [[ ! "$PWD" =~ /var/www/laravel/?$ ]]; then
        print_warning "Current directory is $PWD"
        print_warning "Recommended to run from /var/www or /var/www/laravel"
        read -p "Do you want to continue anyway? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
    
    # Check dependencies
    print_status "Checking required dependencies..."
    if ! check_dependencies; then
        exit 1
    fi
        
    
    # Create laravel directory if needed
    if [[ "$PWD" =~ /var/www/?$ ]]; then
        mkdir -p laravel
        cd laravel
    fi
    
    # Remove existing directory if it exists
    if [ -d "$PROJECT_NAME" ]; then
        print_warning "Directory '$PROJECT_NAME' already exists."
        read -p "Do you want to remove it and start fresh? (y/N): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            sudo rm -rf "$PROJECT_NAME"
            print_success "Removed existing directory"
        else
            print_error "Aborted. Please remove the directory manually or choose a different name."
            exit 1
        fi
    fi
    
    # Clone repository
    print_status "Cloning '$PROJECT_NAME' Laravel repository..."
    if clone_repository; then
        print_success "Successfully cloned repository"
    else
        print_error "Failed to clone repository"
        exit 1
    fi
    
    # Fix Git ownership issue
    print_status "Configuring Git safe directory..."
    sudo git config --global --add safe.directory "$(pwd)"

    # Install Composer dependencies
    print_status "Installing Composer dependencies..."
    if sudo composer install --no-dev --optimize-autoloader; then
        print_success "Composer dependencies installed"
    else
        print_warning "Failed to install some Composer dependencies"
    fi
    
    # Install NPM dependencies
    print_status "Installing NPM dependencies..."
    if sudo npm install; then
        print_success "NPM dependencies installed"
    else
        print_warning "Failed to install NPM dependencies"
    fi
    
    # Setup environment file
    if [ -f ".env.example" ]; then
        print_status "Setting up environment file..."
        sudo cp .env.example .env
        sudo php artisan key:generate
        print_success "Environment file configured"
        print_warning "Please update .env file with your database and other configurations"
    else
        print_warning "No .env.example file found"
    fi
    
    # Set proper permissions
    print_status "Setting proper Laravel permissions..."
    # First set ownership to current user for Git operations
    sudo chown -R $USER:$USER .
    
    if [ -d "storage" ]; then
        sudo chmod -R 775 storage
        sudo chown -R www-data:www-data storage
        print_success "Storage permissions set"
    fi
    
    if [ -d "bootstrap/cache" ]; then
        sudo chmod -R 775 bootstrap/cache
        sudo chown -R www-data:www-data bootstrap/cache
        print_success "Bootstrap cache permissions set"
    fi
    
    # Set web server ownership for specific directories only
    if [ -d "public" ]; then
        sudo chown -R www-data:www-data public
    fi

    print_status "Building Assets ..."
    if sudo npm run build; then
        print_success "Assets built Successfully"
    else
        print_warning "Failed to build Assets"
    fi    

    print_success "=== '$PROJECT_NAME' Laravel $ENVIRONMENT Setup Complete ==="
    print_status "Project location: $(pwd)"
    print_status "Environment: $ENVIRONMENT"
    print_status "Branch: $(sudo git branch --show-current)"
    print_status "Next steps:"
    echo "Configure database settings in .env file"        
}

# Run main function
main
