#!/bin/bash
# QUICK DEPLOYMENT - Copy and paste this entire script

# Variables (UPDATE THESE)
PROJECT_PATH="/home/nashaajo/nashaajobs.com"
VENV_PATH="$PROJECT_PATH/venv"
USER="nashaajo"

echo "Starting deployment..."

# Navigate and activate
cd $PROJECT_PATH
source $VENV_PATH/bin/activate

# Backup
echo "Creating backup..."
python manage.py dumpdata > backup_$(date +%Y%m%d_%H%M%S).json

# Pull code
echo "Pulling latest code..."
git pull origin main

# Install packages
echo "Installing packages..."
pip install channels==4.0.0 daphne==4.0.0

# Migrate
echo "Running migrations..."
python manage.py migrate custom_admin

# Collect static
echo "Collecting static files..."
python manage.py collectstatic --noinput

# Create Daphne service
echo "Creating Daphne service..."
sudo tee /etc/systemd/system/daphne.service > /dev/null <<EOF
[Unit]
Description=Daphne ASGI Server
After=network.target

[Service]
Type=simple
User=$USER
Group=$USER
WorkingDirectory=$PROJECT_PATH
Environment="PATH=$VENV_PATH/bin"
ExecStart=$VENV_PATH/bin/daphne -b 0.0.0.0 -p 8001 config.asgi:application
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
EOF

# Enable and start Daphne
echo "Starting Daphne..."
sudo systemctl daemon-reload
sudo systemctl enable daphne
sudo systemctl start daphne

# Restart Gunicorn
echo "Restarting Gunicorn..."
sudo systemctl restart gunicorn

# Setup cron
echo "Setting up cron job..."
(crontab -l 2>/dev/null | grep -v check_expiring_subscriptions; echo "0 9 * * * cd $PROJECT_PATH && $VENV_PATH/bin/python manage.py check_expiring_subscriptions >> $PROJECT_PATH/logs/cron.log 2>&1") | crontab -

# Create logs directory
mkdir -p $PROJECT_PATH/logs

echo "=========================================="
echo "DEPLOYMENT COMPLETE!"
echo "=========================================="
echo "Services status:"
sudo systemctl status gunicorn --no-pager -l
sudo systemctl status daphne --no-pager -l
echo ""
echo "Next steps:"
echo "1. Update Nginx config for WebSocket"
echo "2. Test at: https://nashaajobs.com/Managenashaajobs/"
echo "3. Check browser console for 'WebSocket connected'"
