#!/bin/bash
# SmoothSchedule Server Initial Setup
# Run this on the production server to install dependencies
# Usage: ssh poduck@smoothschedule.com 'bash -s' < server-setup.sh

set -e

echo "==================================="
echo "SmoothSchedule Server Setup"
echo "==================================="

# Update system
echo ">>> Updating system packages..."
sudo apt-get update
sudo apt-get upgrade -y

# Install Docker
if ! command -v docker &> /dev/null; then
    echo ">>> Installing Docker..."
    curl -fsSL https://get.docker.com -o get-docker.sh
    sudo sh get-docker.sh
    sudo usermod -aG docker $USER
    rm get-docker.sh
    echo "Docker installed!"
else
    echo "Docker already installed."
fi

# Install Docker Compose
if ! command -v docker compose &> /dev/null; then
    echo ">>> Installing Docker Compose..."
    sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    sudo chmod +x /usr/local/bin/docker-compose
    echo "Docker Compose installed!"
else
    echo "Docker Compose already installed."
fi

# Install AWS CLI for DigitalOcean Spaces management
if ! command -v aws &> /dev/null; then
    echo ">>> Installing AWS CLI..."
    sudo apt-get install -y awscli
    echo "AWS CLI installed!"
else
    echo "AWS CLI already installed."
fi

# Install UFW firewall
if ! command -v ufw &> /dev/null; then
    echo ">>> Installing UFW firewall..."
    sudo apt-get install -y ufw
fi

# Configure firewall
echo ">>> Configuring firewall..."
sudo ufw --force enable
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 5555/tcp  # Flower (Celery monitoring)

echo ">>> Firewall configured!"

# Install fail2ban for security
if ! command -v fail2ban-client &> /dev/null; then
    echo ">>> Installing fail2ban..."
    sudo apt-get install -y fail2ban
    sudo systemctl enable fail2ban
    sudo systemctl start fail2ban
    echo "Fail2ban installed!"
else
    echo "Fail2ban already installed."
fi

# Create project directory
echo ">>> Creating project directory..."
mkdir -p ~/smoothschedule
mkdir -p ~/smoothschedule-frontend

echo ""
echo "==================================="
echo "Server Setup Complete!"
echo "==================================="
echo ""
echo "Next steps:"
echo "1. Logout and login again for Docker group changes to take effect"
echo "2. Configure DigitalOcean Spaces: ./setup-spaces.sh"
echo "3. Deploy the application: ./deploy.sh"
echo ""
echo "IMPORTANT: Logout and login now!"
