#!/usr/bin/env bash
##############################################################
# GMLM Platform — Automated Deployment Script
#
# This script provisions a new customer server from scratch.
# Run it on a fresh Ubuntu 22.04 / Debian 12 Linux server.
#
# Usage:
#   chmod +x deploy.sh
#   sudo ./deploy.sh \
#     --domain mlm.customer.com \
#     --company "Customer MLM Solutions" \
#     --email admin@customer.com \
#     --license GMLM-XXXX-XXXX-XXXX \
#     --currency USD
#
# Requirements:
#   - Ubuntu 22.04 LTS or Debian 12
#   - Root or sudo access
#   - Outbound internet access
#   - Domain DNS pointing to this server's IP
##############################################################

set -euo pipefail

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

# ── Defaults ──────────────────────────────────────────────────
DOMAIN=""
COMPANY=""
EMAIL=""
LICENSE=""
CURRENCY="USD"
TIMEZONE="UTC"
INSTALL_DIR="/var/www/gmlm"
DB_NAME="gmlm_$(date +%s)"
DB_USER="gmlm_user"
DB_PASS=$(openssl rand -base64 32 | tr -dc 'A-Za-z0-9' | head -c 32)
DB_ROOT_PASS=$(openssl rand -base64 32 | tr -dc 'A-Za-z0-9' | head -c 32)
REDIS_PASS=$(openssl rand -base64 32 | tr -dc 'A-Za-z0-9' | head -c 32)
DEPLOY_ID="gmlm-$(date +%s)"

# ── Parse arguments ────────────────────────────────────────────
while [[ "$#" -gt 0 ]]; do
    case $1 in
        --domain)    DOMAIN="$2";   shift ;;
        --company)   COMPANY="$2";  shift ;;
        --email)     EMAIL="$2";    shift ;;
        --license)   LICENSE="$2";  shift ;;
        --currency)  CURRENCY="$2"; shift ;;
        --timezone)  TIMEZONE="$2"; shift ;;
        *) echo "Unknown parameter: $1"; exit 1 ;;
    esac
    shift
done

# ── Validate required arguments ───────────────────────────────
if [[ -z "$DOMAIN" || -z "$COMPANY" || -z "$EMAIL" || -z "$LICENSE" ]]; then
    echo -e "${RED}Error: --domain, --company, --email, and --license are required.${NC}"
    echo ""
    echo "Usage: sudo ./deploy.sh --domain mlm.example.com --company 'My MLM' --email admin@example.com --license GMLM-XXXX"
    exit 1
fi

# ── Banner ─────────────────────────────────────────────────────
echo ""
echo -e "${BLUE}╔══════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║   GMLM Platform — Deployment Script      ║${NC}"
echo -e "${BLUE}╚══════════════════════════════════════════╝${NC}"
echo ""
echo -e "${YELLOW}Company:  ${NC}${COMPANY}"
echo -e "${YELLOW}Domain:   ${NC}${DOMAIN}"
echo -e "${YELLOW}Email:    ${NC}${EMAIL}"
echo -e "${YELLOW}Currency: ${NC}${CURRENCY}"
echo ""

step() {
    echo -e "${BLUE}▶ ${NC}$1"
}

success() {
    echo -e "${GREEN}✓ ${NC}$1"
}

# ── Step 1: Install system dependencies ───────────────────────
step "Installing system dependencies..."
apt-get update -qq
apt-get install -qq -y \
    curl wget git unzip software-properties-common \
    ca-certificates gnupg lsb-release apt-transport-https
success "System dependencies installed."

# ── Step 2: Install Docker ────────────────────────────────────
step "Installing Docker..."
if ! command -v docker &>/dev/null; then
    curl -fsSL https://get.docker.com | sh
    usermod -aG docker "$SUDO_USER"
    systemctl enable docker
    systemctl start docker
fi
success "Docker installed."

# ── Step 3: Install Docker Compose ────────────────────────────
step "Installing Docker Compose..."
if ! command -v docker-compose &>/dev/null; then
    COMPOSE_VERSION=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | grep '"tag_name"' | cut -d'"' -f4)
    curl -SL "https://github.com/docker/compose/releases/download/${COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" \
        -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
fi
success "Docker Compose installed."

# ── Step 4: Clone GMLM codebase ───────────────────────────────
step "Setting up GMLM codebase in ${INSTALL_DIR}..."
mkdir -p "${INSTALL_DIR}"

if [[ -d "${INSTALL_DIR}/.git" ]]; then
    cd "${INSTALL_DIR}" && git pull origin main
else
    # In production, clone from your private repository or extract from signed package
    # git clone https://github.com/your-org/gmlm-platform.git "${INSTALL_DIR}"
    cp -r . "${INSTALL_DIR}/"
fi

cd "${INSTALL_DIR}"
success "Codebase ready."

# ── Step 5: Generate .env file ────────────────────────────────
step "Generating environment configuration..."

APP_KEY=$(openssl rand -base64 32)
JWT_SECRET=$(openssl rand -base64 64 | tr -dc 'A-Za-z0-9' | head -c 64)

cat > "${INSTALL_DIR}/.env" << EOF
APP_NAME="${COMPANY}"
APP_ENV=production
APP_KEY=base64:${APP_KEY}
APP_DEBUG=false
APP_URL=https://${DOMAIN}
APP_INSTALLED=false
APP_TIMEZONE=${TIMEZONE}
APP_LOCALE=en

GMLM_LICENSE_KEY=${LICENSE}
GMLM_VERSION=1.0.0
GMLM_UPDATE_SERVER=https://updates.globalmlmsoftware.com
GMLM_BASE_CURRENCY=${CURRENCY}
DEPLOYMENT_ID=${DEPLOY_ID}

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=${DB_NAME}
DB_USERNAME=${DB_USER}
DB_PASSWORD=${DB_PASS}
DB_ROOT_PASSWORD=${DB_ROOT_PASS}

REDIS_HOST=redis
REDIS_PASSWORD=${REDIS_PASS}
REDIS_PORT=6379

CACHE_DRIVER=redis
SESSION_DRIVER=redis
SESSION_LIFETIME=120
QUEUE_CONNECTION=redis

MAIL_MAILER=log
MAIL_FROM_ADDRESS="noreply@${DOMAIN}"
MAIL_FROM_NAME="${COMPANY}"

FILESYSTEM_DISK=local

HTTP_PORT=80
HTTPS_PORT=443

LOG_CHANNEL=daily
LOG_LEVEL=warning

JWT_SECRET=${JWT_SECRET}

OCTANE_ENABLED=false
EOF

success ".env file generated."

# ── Step 6: Create storage directories ────────────────────────
step "Creating storage directories..."
mkdir -p "${INSTALL_DIR}/docker/nginx/certs"
mkdir -p "${INSTALL_DIR}/storage"/{app/{public,private,kyc,exports},logs,framework/{cache,sessions,views}}
mkdir -p "${INSTALL_DIR}/bootstrap/cache"
chown -R www-data:www-data "${INSTALL_DIR}/storage" "${INSTALL_DIR}/bootstrap/cache" 2>/dev/null || true
success "Storage directories created."

# ── Step 7: Start Docker containers ───────────────────────────
step "Starting Docker containers..."
cd "${INSTALL_DIR}"
docker compose pull
docker compose up -d --build

# Wait for MySQL to be healthy
echo "  Waiting for MySQL to be ready..."
timeout 60 bash -c "until docker compose exec -T mysql mysqladmin ping -h localhost --silent 2>/dev/null; do sleep 2; done"
success "All containers running."

# ── Step 8: Run provisioning ───────────────────────────────────
step "Running GMLM provisioning wizard..."
echo "  Note: You will be prompted for an admin password."
docker compose exec app php artisan gmlm:provision \
    --company="${COMPANY}" \
    --domain="${DOMAIN}" \
    --email="${EMAIL}" \
    --currency="${CURRENCY}" \
    --timezone="${TIMEZONE}" \
    --license="${LICENSE}" \
    --force
success "Provisioning complete."

# ── Step 9: Install SSL certificate ───────────────────────────
step "Setting up SSL certificate with Let's Encrypt..."
if command -v certbot &>/dev/null; then
    # Stop Nginx temporarily for certbot standalone
    docker compose stop app
    certbot certonly \
        --standalone \
        --non-interactive \
        --agree-tos \
        --email "${EMAIL}" \
        -d "${DOMAIN}"

    # Copy certificates to the expected path
    cp "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem" "${INSTALL_DIR}/docker/nginx/certs/"
    cp "/etc/letsencrypt/live/${DOMAIN}/privkey.pem"   "${INSTALL_DIR}/docker/nginx/certs/"

    docker compose start app
    success "SSL certificate installed."

    # Set up auto-renewal
    echo "0 3 * * * certbot renew --quiet && cp /etc/letsencrypt/live/${DOMAIN}/fullchain.pem ${INSTALL_DIR}/docker/nginx/certs/ && cp /etc/letsencrypt/live/${DOMAIN}/privkey.pem ${INSTALL_DIR}/docker/nginx/certs/ && cd ${INSTALL_DIR} && docker compose exec app nginx -s reload" \
        | crontab -
    success "SSL auto-renewal configured."
else
    apt-get install -qq -y certbot
    step "Certbot installed. Run the SSL step again or place certificates in ${INSTALL_DIR}/docker/nginx/certs/"
fi

# ── Step 10: Configure firewall ────────────────────────────────
step "Configuring UFW firewall..."
if command -v ufw &>/dev/null; then
    ufw allow 22/tcp   comment "SSH"
    ufw allow 80/tcp   comment "HTTP"
    ufw allow 443/tcp  comment "HTTPS"
    ufw --force enable
    success "Firewall configured."
fi

# ── Step 11: Run health check ──────────────────────────────────
step "Running deployment health check..."
sleep 5
docker compose exec app php artisan gmlm:health
success "Health check complete."

# ── Summary ────────────────────────────────────────────────────
echo ""
echo -e "${GREEN}╔══════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║   GMLM Deployment Complete!              ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════╝${NC}"
echo ""
echo -e "${YELLOW}Platform URL:   ${NC}https://${DOMAIN}"
echo -e "${YELLOW}Admin Login:    ${NC}https://${DOMAIN}/admin/dashboard"
echo -e "${YELLOW}Admin Email:    ${NC}${EMAIL}"
echo -e "${YELLOW}Install Dir:    ${NC}${INSTALL_DIR}"
echo -e "${YELLOW}Deploy ID:      ${NC}${DEPLOY_ID}"
echo ""
echo -e "${RED}IMPORTANT — Save these credentials securely:${NC}"
echo -e "  DB Password:    ${DB_PASS}"
echo -e "  Redis Password: ${REDIS_PASS}"
echo ""
echo -e "Log files:    docker compose logs -f"
echo -e "Health check: docker compose exec app php artisan gmlm:health"
echo ""

# Save credentials to a secure file (readable by root only)
CREDS_FILE="${INSTALL_DIR}/.deployment-credentials"
cat > "${CREDS_FILE}" << EOF
DEPLOYMENT_ID=${DEPLOY_ID}
DOMAIN=${DOMAIN}
COMPANY=${COMPANY}
DB_NAME=${DB_NAME}
DB_USER=${DB_USER}
DB_PASS=${DB_PASS}
DB_ROOT_PASS=${DB_ROOT_PASS}
REDIS_PASS=${REDIS_PASS}
DEPLOYED_AT=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
EOF
chmod 600 "${CREDS_FILE}"
echo -e "${YELLOW}Credentials saved to: ${CREDS_FILE} (root-readable only)${NC}"
