#!/bin/bash

# AirwavePBX v2.1.1 Build Script - With Real Asterisk Integration
# This version includes actual PBX functionality

set -e

echo "Building AirwavePBX v2.1.1 with Asterisk Integration..."

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

# Clean previous builds
echo -e "${YELLOW}Cleaning previous builds...${NC}"
rm -rf airwavepbx-v2.1.1-asterisk
rm -f airwavepbx-v2.1.1-asterisk.tar.gz

# Create build directory
mkdir -p airwavepbx-v2.1.1-asterisk

# Copy source files
echo -e "${YELLOW}Copying source files...${NC}"
cp -r src airwavepbx-v2.1.1-asterisk/
cp -r public airwavepbx-v2.1.1-asterisk/
cp -r app airwavepbx-v2.1.1-asterisk/ 2>/dev/null || true
cp package*.json airwavepbx-v2.1.1-asterisk/
cp tsconfig.json airwavepbx-v2.1.1-asterisk/
cp next.config.js airwavepbx-v2.1.1-asterisk/
cp tailwind.config.js airwavepbx-v2.1.1-asterisk/
cp postcss.config.js airwavepbx-v2.1.1-asterisk/
cp .eslintrc.json airwavepbx-v2.1.1-asterisk/ 2>/dev/null || true

# Create components directory if needed
mkdir -p airwavepbx-v2.1.1-asterisk/components

# Copy any component files
if [ -d "v2.1.0-components" ]; then
    cp -r v2.1.0-components/* airwavepbx-v2.1.1-asterisk/components/ 2>/dev/null || true
fi

# Create .env.example
cat > airwavepbx-v2.1.1-asterisk/.env.example << 'EOF'
# Database
DATABASE_URL="file:./airwavepbx.db"

# Authentication
JWT_SECRET="your-super-secret-jwt-key-change-this"
NEXTAUTH_SECRET="your-nextauth-secret-change-this"
NEXTAUTH_URL="http://localhost:3000"

# Asterisk AMI Configuration
ASTERISK_HOST=localhost
ASTERISK_AMI_PORT=5038
ASTERISK_AMI_USERNAME=airwavepbx
ASTERISK_AMI_PASSWORD=your-ami-password

# API Configuration
API_PORT=3001
API_BASE_URL=http://localhost:3001

# Production
NODE_ENV=production
EOF

# Create the enhanced installer with Asterisk setup
cat > airwavepbx-v2.1.1-asterisk/install.sh << 'INSTALLER_EOF'
#!/bin/bash

# AirwavePBX v2.1.1 Installer - With Asterisk Integration
# For Ubuntu 24.04 LTS

set -e

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

# Variables
INSTALL_DIR="/opt/airwavepbx"
SERVICE_USER="airwavepbx"
ASTERISK_VERSION="20"
NODE_VERSION="22"

echo -e "${BLUE}=====================================${NC}"
echo -e "${BLUE}AirwavePBX v2.1.1 Installer${NC}"
echo -e "${BLUE}With Full Asterisk Integration${NC}"
echo -e "${BLUE}=====================================${NC}"
echo ""

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

# Detect installation mode
if [ -d "$INSTALL_DIR" ]; then
    echo -e "${YELLOW}Existing installation detected.${NC}"
    echo "Select action:"
    echo "1) Upgrade existing installation"
    echo "2) Clean install (removes existing)"
    echo "3) Cancel"
    read -p "Choice (1-3): " INSTALL_MODE
else
    INSTALL_MODE="1"
fi

case $INSTALL_MODE in
    2)
        echo -e "${YELLOW}Performing clean installation...${NC}"
        systemctl stop airwavepbx airwavepbx-api || true
        rm -rf $INSTALL_DIR
        ;;
    3)
        echo "Installation cancelled."
        exit 0
        ;;
esac

# Update system
echo -e "${YELLOW}Updating system packages...${NC}"
apt update
apt upgrade -y

# Install dependencies
echo -e "${YELLOW}Installing system dependencies...${NC}"
apt install -y curl wget git build-essential nginx sqlite3 certbot \
    python3-certbot-nginx ufw fail2ban software-properties-common \
    sox mpg123 ffmpeg

# Install Asterisk 20 LTS
echo -e "${YELLOW}Installing Asterisk ${ASTERISK_VERSION} LTS...${NC}"
if ! command -v asterisk &> /dev/null; then
    add-apt-repository -y universe
    apt update
    apt install -y asterisk asterisk-core-sounds-en asterisk-core-sounds-en-wav \
        asterisk-core-sounds-en-gsm asterisk-moh-opsound-wav asterisk-moh-opsound-gsm
fi

# Configure Asterisk for AirwavePBX
echo -e "${YELLOW}Configuring Asterisk...${NC}"

# Backup existing Asterisk configs
if [ -d "/etc/asterisk" ]; then
    cp -r /etc/asterisk /etc/asterisk.backup.$(date +%Y%m%d_%H%M%S)
fi

# Enable AMI (Asterisk Manager Interface)
cat > /etc/asterisk/manager.conf << 'EOF'
[general]
enabled = yes
port = 5038
bindaddr = 127.0.0.1

[airwavepbx]
secret = $(openssl rand -base64 32)
deny = 0.0.0.0/0.0.0.0
permit = 127.0.0.1/255.255.255.0
read = all
write = all
writetimeout = 5000
EOF

# Create AirwavePBX user for Asterisk
if ! id -u asterisk > /dev/null 2>&1; then
    useradd -r -s /bin/false -d /var/lib/asterisk asterisk
fi

# Set permissions
chown -R asterisk:asterisk /etc/asterisk
chown -R asterisk:asterisk /var/lib/asterisk
chown -R asterisk:asterisk /var/spool/asterisk

# Install Node.js 22 LTS
echo -e "${YELLOW}Installing Node.js ${NODE_VERSION} LTS...${NC}"
if ! command -v node &> /dev/null || [ $(node -v | cut -d'v' -f2 | cut -d'.' -f1) -lt 22 ]; then
    curl -fsSL https://deb.nodesource.com/setup_${NODE_VERSION}.x | bash -
    apt install -y nodejs
fi

# Update npm
echo -e "${YELLOW}Updating npm to latest...${NC}"
npm install -g npm@latest

# Create application user
if ! id "$SERVICE_USER" &>/dev/null; then
    useradd -r -s /bin/false -m -d /home/$SERVICE_USER $SERVICE_USER
fi

# Create directory structure
echo -e "${YELLOW}Creating directory structure...${NC}"
mkdir -p $INSTALL_DIR
mkdir -p /var/log/airwavepbx
mkdir -p /var/lib/airwavepbx
mkdir -p /etc/airwavepbx

# Copy application files
echo -e "${YELLOW}Installing application files...${NC}"
cp -r * $INSTALL_DIR/
chown -R $SERVICE_USER:$SERVICE_USER $INSTALL_DIR
chown -R $SERVICE_USER:$SERVICE_USER /var/log/airwavepbx
chown -R $SERVICE_USER:$SERVICE_USER /var/lib/airwavepbx

# Setup environment
cd $INSTALL_DIR
if [ ! -f .env ]; then
    cp .env.example .env
    
    # Generate secure secrets
    JWT_SECRET=$(openssl rand -base64 32)
    NEXTAUTH_SECRET=$(openssl rand -base64 32)
    AMI_PASSWORD=$(grep "secret = " /etc/asterisk/manager.conf | head -1 | cut -d' ' -f3)
    
    # Update .env file
    sed -i "s/your-super-secret-jwt-key-change-this/$JWT_SECRET/" .env
    sed -i "s/your-nextauth-secret-change-this/$NEXTAUTH_SECRET/" .env
    sed -i "s/your-ami-password/$AMI_PASSWORD/" .env
fi

# Install dependencies
echo -e "${YELLOW}Installing Node.js dependencies...${NC}"
sudo -u $SERVICE_USER npm install --production

# Build the application
echo -e "${YELLOW}Building application...${NC}"
sudo -u $SERVICE_USER npm run build

# Initialize database
echo -e "${YELLOW}Initializing database...${NC}"
sudo -u $SERVICE_USER npm run db:init || true

# Create systemd services
echo -e "${YELLOW}Creating systemd services...${NC}"

# Frontend service
cat > /etc/systemd/system/airwavepbx.service << EOF
[Unit]
Description=AirwavePBX Web Interface
After=network.target asterisk.service

[Service]
Type=simple
User=$SERVICE_USER
WorkingDirectory=$INSTALL_DIR
Environment="NODE_ENV=production"
Environment="PORT=3000"
ExecStart=/usr/bin/npm start
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

# API service
cat > /etc/systemd/system/airwavepbx-api.service << EOF
[Unit]
Description=AirwavePBX API Server
After=network.target asterisk.service

[Service]
Type=simple
User=$SERVICE_USER
WorkingDirectory=$INSTALL_DIR
Environment="NODE_ENV=production"
Environment="API_PORT=3001"
ExecStart=/usr/bin/node src/api/server.js
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

# Configure Nginx
echo -e "${YELLOW}Configuring Nginx...${NC}"
cat > /etc/nginx/sites-available/airwavepbx << 'EOF'
server {
    listen 80;
    server_name _;
    
    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    
    # Frontend
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
    # API
    location /api {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
    # WebSocket support
    location /socket.io {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
EOF

# Enable site
ln -sf /etc/nginx/sites-available/airwavepbx /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

# Configure firewall
echo -e "${YELLOW}Configuring firewall...${NC}"
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw allow 5060/udp
ufw allow 10000:20000/udp
ufw --force enable

# Start services
echo -e "${YELLOW}Starting services...${NC}"
systemctl daemon-reload
systemctl enable asterisk
systemctl restart asterisk
systemctl enable airwavepbx airwavepbx-api
systemctl start airwavepbx airwavepbx-api
systemctl restart nginx

# Create admin user
echo -e "${YELLOW}Creating admin user...${NC}"
cd $INSTALL_DIR
ADMIN_PASSWORD=$(openssl rand -base64 12)
sudo -u $SERVICE_USER npm run create-admin -- --username admin --password "$ADMIN_PASSWORD" || true

# Get AMI password for display
AMI_PASSWORD=$(grep "secret = " /etc/asterisk/manager.conf | grep -A1 "\[airwavepbx\]" | tail -1 | cut -d' ' -f3)

# Installation complete
echo ""
echo -e "${GREEN}=====================================${NC}"
echo -e "${GREEN}Installation Complete!${NC}"
echo -e "${GREEN}=====================================${NC}"
echo ""
echo -e "${BLUE}Access your PBX at:${NC} http://$(hostname -I | awk '{print $1}')"
echo ""
echo -e "${BLUE}Login Credentials:${NC}"
echo "Username: admin"
echo "Password: $ADMIN_PASSWORD"
echo ""
echo -e "${BLUE}Asterisk AMI Credentials:${NC}"
echo "Username: airwavepbx"
echo "Password: $AMI_PASSWORD"
echo ""
echo -e "${YELLOW}Important:${NC} Save these credentials!"
echo ""
echo -e "${BLUE}Services Status:${NC}"
systemctl --no-pager status airwavepbx airwavepbx-api asterisk

echo ""
echo -e "${GREEN}To configure SSL:${NC}"
echo "sudo certbot --nginx -d your-domain.com"

echo ""
echo -e "${GREEN}Next Steps:${NC}"
echo "1. Login to the web interface"
echo "2. Create extensions"
echo "3. Configure trunks"
echo "4. Set up inbound/outbound routes"
echo "5. Test with IP phones or softphones"
INSTALLER_EOF

chmod +x airwavepbx-v2.1.1-asterisk/install.sh

# Create database initialization script
cat > airwavepbx-v2.1.1-asterisk/init-db.sql << 'EOF'
-- AirwavePBX Database Schema
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE NOT NULL,
    password TEXT NOT NULL,
    email TEXT,
    role TEXT DEFAULT 'user',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS extensions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    extension TEXT UNIQUE NOT NULL,
    name TEXT NOT NULL,
    password TEXT NOT NULL,
    context TEXT DEFAULT 'internal',
    callerid TEXT,
    voicemail BOOLEAN DEFAULT 1,
    recording BOOLEAN DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS trunks (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    type TEXT NOT NULL,
    host TEXT NOT NULL,
    username TEXT,
    password TEXT,
    context TEXT DEFAULT 'inbound',
    codecs TEXT DEFAULT 'ulaw,alaw',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS routes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    type TEXT NOT NULL, -- 'inbound' or 'outbound'
    pattern TEXT NOT NULL,
    destination TEXT NOT NULL,
    priority INTEGER DEFAULT 0,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS cdr (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    calldate DATETIME NOT NULL,
    clid TEXT,
    src TEXT,
    dst TEXT,
    dcontext TEXT,
    channel TEXT,
    dstchannel TEXT,
    lastapp TEXT,
    lastdata TEXT,
    duration INTEGER,
    billsec INTEGER,
    disposition TEXT,
    amaflags INTEGER,
    uniqueid TEXT,
    userfield TEXT
);

-- Create indexes
CREATE INDEX idx_extensions_extension ON extensions(extension);
CREATE INDEX idx_cdr_calldate ON cdr(calldate);
CREATE INDEX idx_cdr_src ON cdr(src);
CREATE INDEX idx_cdr_dst ON cdr(dst);
EOF

# Update package.json version
cd airwavepbx-v2.1.1-asterisk
sed -i 's/"version": "2.1.0"/"version": "2.1.1"/' package.json

# Create README for this version
cat > README-ASTERISK.md << 'EOF'
# AirwavePBX v2.1.1 - Asterisk Integration Edition

This version includes FULL Asterisk integration, making it a complete PBX solution.

## New Features

### Real Asterisk Integration
- AMI (Asterisk Manager Interface) connection
- Real-time call monitoring and control
- Automatic configuration file generation
- Extension provisioning with PJSIP
- Trunk configuration
- Call routing (inbound/outbound)

### What Works Now
1. **Extension Management**
   - Creates real Asterisk endpoints
   - Generates PJSIP configurations
   - Auto-reload of Asterisk
   
2. **Call Control**
   - Monitor active calls
   - Hangup calls
   - Transfer calls
   - Originate calls

3. **Real-time Events**
   - Extension status updates
   - Call start/end notifications
   - WebSocket integration

### Asterisk Configuration
The system automatically configures:
- `/etc/asterisk/pjsip_endpoints.conf` - Extensions
- `/etc/asterisk/pjsip_trunks.conf` - Trunks  
- `/etc/asterisk/extensions_custom.conf` - Dialplan
- `/etc/asterisk/manager.conf` - AMI access

### Testing Your PBX
1. Create an extension in the web UI
2. Configure a SIP phone with the credentials
3. Make test calls between extensions
4. Check real-time call status in dashboard

### API Endpoints
All endpoints now interact with real Asterisk:
- `POST /api/extensions` - Creates real extension
- `GET /api/calls/active` - Shows live calls
- `POST /api/calls/:id/hangup` - Hangs up active call
- `POST /api/trunks` - Configures SIP trunk

### Next Development Steps
- IVR builder
- Conference bridges
- Call queues
- Call recording playback
- Voicemail management
- Advanced routing rules

This is now a functional PBX that can replace FreePBX for basic operations!
EOF

echo -e "${GREEN}✓ Build complete!${NC}"
echo -e "${YELLOW}Package created: airwavepbx-v2.1.1-asterisk${NC}"

# Create tarball
echo -e "${YELLOW}Creating distribution package...${NC}"
tar -czf airwavepbx-v2.1.1-asterisk.tar.gz airwavepbx-v2.1.1-asterisk/

echo -e "${GREEN}✓ Package ready: airwavepbx-v2.1.1-asterisk.tar.gz${NC}"
echo ""
echo "This version includes:"
echo "- Real Asterisk AMI integration"
echo "- Automatic PJSIP configuration"
echo "- Live call monitoring"
echo "- Extension provisioning"
echo "- Trunk management"
echo ""
echo "To install: tar -xzf airwavepbx-v2.1.1-asterisk.tar.gz && cd airwavepbx-v2.1.1-asterisk && sudo ./install.sh"