#!/bin/bash
# Deploy Ginxsom to local installation directory
# Builds static binary and deploys to ~/Storage/Blossom

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEPLOY_DIR="$HOME/Storage/Blossom"
SERVICE_NAME="ginxsom.service"
NGINX_SITE_NAME="ginxsom"
NGINX_PORT="9443"

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

echo -e "${YELLOW}=== Ginxsom Local Deployment ===${NC}"
echo "Source: $SCRIPT_DIR"
echo "Target: $DEPLOY_DIR"
echo "Nginx Port: $NGINX_PORT"
echo ""

# Step 1: Build static binary
echo -e "${YELLOW}Step 1: Building static binary...${NC}"
cd "$SCRIPT_DIR"
./build_static.sh

if [ $? -ne 0 ]; then
    echo -e "${RED}Build failed! Cannot continue.${NC}"
    exit 1
fi
echo -e "${GREEN}✓ Build complete${NC}"
echo ""

# Step 2: Create deployment directory
echo -e "${YELLOW}Step 2: Preparing deployment directory...${NC}"
mkdir -p "$DEPLOY_DIR"
mkdir -p "$DEPLOY_DIR/blobs"
mkdir -p "$DEPLOY_DIR/db"
mkdir -p "$DEPLOY_DIR/logs"
echo -e "${GREEN}✓ Directories created${NC}"
echo ""

# Step 3: Stop service before copying binary
echo -e "${YELLOW}Step 3: Stopping service before binary update...${NC}"
if systemctl list-unit-files | grep -q "$SERVICE_NAME"; then
    sudo systemctl stop "$SERVICE_NAME" || true
    sleep 1
    echo -e "${GREEN}✓ Service stopped${NC}"
fi
echo ""

# Step 4: Copy binary
echo -e "${YELLOW}Step 4: Copying binary...${NC}"

# Detect architecture
ARCH=$(uname -m)
case "$ARCH" in
    x86_64) BINARY_NAME="ginxsom-fcgi_static_x86_64" ;;
    aarch64|arm64) BINARY_NAME="ginxsom-fcgi_static_arm64" ;;
    *) BINARY_NAME="ginxsom-fcgi_static_${ARCH}" ;;
esac

SOURCE_BINARY="$SCRIPT_DIR/build/$BINARY_NAME"
TARGET_BINARY="$DEPLOY_DIR/ginxsom"

if [ ! -f "$SOURCE_BINARY" ]; then
    echo -e "${RED}Error: Binary not found at $SOURCE_BINARY${NC}"
    exit 1
fi

cp "$SOURCE_BINARY" "$TARGET_BINARY"
chmod +x "$TARGET_BINARY"
echo -e "${GREEN}✓ Binary copied to $TARGET_BINARY${NC}"
echo ""

# Step 5: Copy configuration files if they exist
echo -e "${YELLOW}Step 5: Copying configuration files...${NC}"
if [ -f "$SCRIPT_DIR/mime.types" ]; then
    cp "$SCRIPT_DIR/mime.types" "$DEPLOY_DIR/"
    echo "  - mime.types"
fi
if [ -f "$SCRIPT_DIR/.admin_keys" ]; then
    cp "$SCRIPT_DIR/.admin_keys" "$DEPLOY_DIR/"
    chmod 600 "$DEPLOY_DIR/.admin_keys"
    echo "  - .admin_keys"
fi
if [ -f "$SCRIPT_DIR/config/fastcgi_params" ]; then
    cp "$SCRIPT_DIR/config/fastcgi_params" "$DEPLOY_DIR/"
    echo "  - fastcgi_params"
fi
echo -e "${GREEN}✓ Configuration files copied${NC}"
echo ""

# Step 6: Setup nginx configuration
echo -e "${YELLOW}Step 6: Setting up nginx configuration...${NC}"

# Copy nginx config to sites-available
if [ -f "$SCRIPT_DIR/config/ginxsom-local.conf" ]; then
    sudo cp "$SCRIPT_DIR/config/ginxsom-local.conf" "/etc/nginx/sites-available/$NGINX_SITE_NAME"
    echo "  - Copied nginx config to sites-available"
    
    # Create symlink in sites-enabled if it doesn't exist
    if [ ! -L "/etc/nginx/sites-enabled/$NGINX_SITE_NAME" ]; then
        sudo ln -s "/etc/nginx/sites-available/$NGINX_SITE_NAME" "/etc/nginx/sites-enabled/$NGINX_SITE_NAME"
        echo "  - Created symlink in sites-enabled"
    else
        echo "  - Symlink already exists in sites-enabled"
    fi
    
    # Test nginx configuration
    echo "  - Testing nginx configuration..."
    if sudo nginx -t; then
        echo -e "${GREEN}✓ Nginx configuration valid${NC}"
    else
        echo -e "${RED}✗ Nginx configuration test failed${NC}"
        exit 1
    fi
else
    echo -e "${YELLOW}Warning: nginx config not found at $SCRIPT_DIR/config/ginxsom-local.conf${NC}"
fi
echo ""

# Step 7: Restart service
echo -e "${YELLOW}Step 7: Restarting service...${NC}"

# Check if service exists
if systemctl list-unit-files | grep -q "$SERVICE_NAME"; then
    echo "Stopping service..."
    sudo systemctl stop "$SERVICE_NAME" || true
    
    echo "Reloading systemd daemon..."
    sudo systemctl daemon-reload
    
    echo "Starting service..."
    sudo systemctl start "$SERVICE_NAME"
    
    # Wait a moment for service to start
    sleep 2
    
    # Check status
    if systemctl is-active --quiet "$SERVICE_NAME"; then
        echo -e "${GREEN}✓ Service started successfully${NC}"
        systemctl status "$SERVICE_NAME" --no-pager -l
    else
        echo -e "${RED}✗ Service failed to start${NC}"
        echo "Check logs with: journalctl -u $SERVICE_NAME -n 50"
        exit 1
    fi
else
    echo -e "${YELLOW}Service not found. Install with:${NC}"
    echo "  sudo cp ginxsom-local.service /etc/systemd/system/ginxsom.service"
    echo "  sudo systemctl daemon-reload"
    echo "  sudo systemctl enable ginxsom.service"
    echo "  sudo systemctl start ginxsom.service"
fi

echo ""

# Step 8: Start/restart nginx
echo -e "${YELLOW}Step 8: Starting nginx...${NC}"
if systemctl is-active --quiet nginx; then
    echo "Reloading nginx..."
    sudo systemctl reload nginx
else
    echo "Starting nginx..."
    sudo systemctl start nginx
fi

if systemctl is-active --quiet nginx; then
    echo -e "${GREEN}✓ Nginx is running${NC}"
else
    echo -e "${RED}✗ Nginx failed to start${NC}"
    exit 1
fi
echo ""

echo -e "${GREEN}=== Deployment complete ===${NC}"
echo ""
echo "Service Information:"
echo "  FastCGI Service: $SERVICE_NAME"
echo "  Nginx Port: $NGINX_PORT"
echo "  Socket: /tmp/ginxsom.sock"
echo "  Storage: $DEPLOY_DIR/blobs"
echo "  Database: $DEPLOY_DIR/db"
echo ""
echo "Service commands:"
echo "  Status:  systemctl status $SERVICE_NAME"
echo "  Stop:    sudo systemctl stop $SERVICE_NAME"
echo "  Start:   sudo systemctl start $SERVICE_NAME"
echo "  Restart: sudo systemctl restart $SERVICE_NAME"
echo "  Logs:    journalctl -u $SERVICE_NAME -f"
echo ""
echo "Nginx commands:"
echo "  Status:  systemctl status nginx"
echo "  Reload:  sudo systemctl reload nginx"
echo "  Logs:    sudo tail -f /var/log/nginx/error.log"
echo ""
echo "Test the server:"
echo "  curl -k https://localhost:$NGINX_PORT/health"
echo "  curl -k https://localhost:$NGINX_PORT/"
