#!/bin/bash
# Full automated deployment script
# This script automates most of the deployment process

set -e

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
DEPLOYMENT_DIR="$( cd "$SCRIPT_DIR/.." && pwd )"
PROJECT_ROOT="$( cd "$DEPLOYMENT_DIR/.." && pwd )"

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

echo -e "${GREEN}=== Full Deployment Script ===${NC}"
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}Please run as root${NC}"
    exit 1
fi

# Phase 1: Install dependencies
echo -e "${YELLOW}Phase 1: Installing dependencies...${NC}"
"$SCRIPT_DIR/../scripts/setup.sh" || {
    echo "Installing dependencies manually..."
    apt update
    apt install -y curl wget git vim net-tools ufw fail2ban \
        unattended-upgrades apt-transport-https ca-certificates \
        gnupg lsb-release software-properties-common
}

# Phase 2: Install Go, Node.js, Docker
echo -e "${YELLOW}Phase 2: Installing development tools...${NC}"
# These would be installed by setup.sh or manually
echo "Please ensure Go, Node.js, and Docker are installed"
echo "Run: ./scripts/check-requirements.sh"

# Phase 3: Setup Nginx
echo -e "${YELLOW}Phase 3: Setting up Nginx...${NC}"
"$SCRIPT_DIR/setup-nginx.sh"

# Phase 4: Install services
echo -e "${YELLOW}Phase 4: Installing systemd services...${NC}"
"$SCRIPT_DIR/install-services.sh"

# Phase 5: Setup firewall
echo -e "${YELLOW}Phase 5: Setting up firewall...${NC}"
"$SCRIPT_DIR/setup-firewall.sh"

# Phase 6: Setup backups
echo -e "${YELLOW}Phase 6: Setting up backups...${NC}"
"$SCRIPT_DIR/setup-backup.sh"

# Phase 7: Setup health checks
echo -e "${YELLOW}Phase 7: Setting up health checks...${NC}"
"$SCRIPT_DIR/setup-health-check.sh"

# Phase 8: Cloudflare Tunnel (optional, interactive)
echo -e "${YELLOW}Phase 8: Cloudflare Tunnel setup (optional)...${NC}"
read -p "Do you want to set up Cloudflare Tunnel now? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    "$SCRIPT_DIR/setup-cloudflare-tunnel.sh"
fi

echo ""
echo -e "${GREEN}=== Deployment Complete ===${NC}"
echo ""
echo "Next steps:"
echo "1. Configure .env file: /home/explorer/explorer-monorepo/.env"
echo "2. Run database migrations"
echo "3. Build applications"
echo "4. Start services: systemctl start explorer-indexer explorer-api solacescanscout-frontend"
echo "5. Configure Cloudflare DNS and SSL"
echo ""
echo "See DEPLOYMENT_GUIDE.md for detailed instructions"
