#!/bin/bash
# networkman-install.sh

echo "🚀 NetworkMan Auto-Installer"
echo "============================="

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "❌ Please run as root (sudo ./networkman-install.sh)"
    exit 1
fi

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

# Log function
log() {
    echo -e "${GREEN}[✓]${NC} $1"
}

error() {
    echo -e "${RED}[✗]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[!]${NC} $1"
}

# Get installation details
read -p "Enter domain/subdomain (e.g., wifi.yourcompany.com): " DOMAIN
read -p "Enter admin email: " ADMIN_EMAIL
read -p "Enter license key from your control panel: " LICENSE_KEY

# Validate license key
if [[ ! $LICENSE_KEY =~ ^NM_[A-Z0-9]{6,}$ ]]; then
    error "Invalid license key format"
    exit 1
fi

log "Starting NetworkMan installation..."

# Update system
log "Updating system packages..."
apt update && apt upgrade -y

# Install required packages
log "Installing required packages..."
apt install -y \
    apache2 \
    mysql-server \
    php8.1 \
    php8.1-mysql \
    php8.1-curl \
    php8.1-json \
    php8.1-mbstring \
    php8.1-xml \
    php8.1-zip \
    php8.1-gd \
    composer \
    certbot \
    python3-certbot-apache

# Configure Apache
log "Configuring Apache..."
a2enmod rewrite
a2enmod ssl
systemctl restart apache2

# Create database
log "Creating database..."
mysql -e "CREATE DATABASE IF NOT EXISTS networkman_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
mysql -e "CREATE USER IF NOT EXISTS 'networkman_user'@'localhost' IDENTIFIED BY '$(openssl rand -base64 12)';"
mysql -e "GRANT ALL PRIVILEGES ON networkman_db.* TO 'networkman_user'@'localhost';"
mysql -e "FLUSH PRIVILEGES;"

# Download and extract NetworkMan
log "Downloading NetworkMan..."
cd /var/www
wget -O networkman-latest.tar.gz https://networkman.startv.al/downloads/networkman-latest.tar.gz
tar -xzf networkman-latest.tar.gz
rm networkman-latest.tar.gz
mv networkman-* networkman

# Set permissions
log "Setting permissions..."
chown -R www-data:www-data /var/www/networkman
chmod -R 755 /var/www/networkman

# Create configuration
log "Creating configuration..."
cat > /var/www/networkman/config.php << EOF
<?php
// NetworkMan Configuration
define('DB_HOST', 'localhost');
define('DB_NAME', 'networkman_db');
define('DB_USER', 'networkman_user');
define('DB_PASS', '$(mysql -N -e "SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(PASSWORD, '\'', 2), '\'', -1) FROM mysql.user WHERE User='networkman_user'")');

define('APP_URL', 'https://$DOMAIN');
define('LICENSE_KEY', '$LICENSE_KEY');
define('ADMIN_EMAIL', '$ADMIN_EMAIL');

define('TIMEZONE', 'Europe/Tirane');
define('CURRENCY', 'EUR');
EOF

# Configure Apache virtual host
log "Configuring virtual host..."
cat > /etc/apache2/sites-available/networkman.conf << EOF
<VirtualHost *:80>
    ServerName $DOMAIN
    Redirect permanent / https://$DOMAIN/
</VirtualHost>

<VirtualHost *:443>
    ServerName $DOMAIN
    DocumentRoot /var/www/networkman/public
    
    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
    SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
    
    <Directory /var/www/networkman/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    ErrorLog \${APACHE_LOG_DIR}/networkman_error.log
    CustomLog \${APACHE_LOG_DIR}/networkman_access.log combined
</VirtualHost>
EOF

a2ensite networkman.conf
a2dissite 000-default.conf
systemctl reload apache2

# Install SSL certificate
log "Installing SSL certificate..."
certbot --apache --non-interactive --agree-tos --email $ADMIN_EMAIL -d $DOMAIN

# Import database schema
log "Importing database schema..."
mysql networkman_db < /var/www/networkman/database/schema.sql

# Install PHP dependencies
log "Installing PHP dependencies..."
cd /var/www/networkman
composer install --no-dev --optimize-autoloader

# Create admin user
log "Creating admin user..."
ADMIN_PASS=$(openssl rand -base64 12)
mysql networkman_db << EOF
INSERT INTO users (username, email, password_hash, role, is_active) 
VALUES ('admin', '$ADMIN_EMAIL', '$(php -r "echo password_hash('$ADMIN_PASS', PASSWORD_DEFAULT);")', 'admin', 1);
EOF

# Create cron job for license validation
log "Setting up cron jobs..."
(crontab -l 2>/dev/null; echo "0 */6 * * * curl -s https://$DOMAIN/api/license/validate > /dev/null 2>&1") | crontab -

# Create backup script
log "Creating backup script..."
cat > /usr/local/bin/networkman-backup << 'EOF'
#!/bin/bash
BACKUP_DIR="/var/backups/networkman"
DATE=$(date +%Y%m%d_%H%M%S)
mkdir -p $BACKUP_DIR

# Backup database
mysqldump networkman_db > $BACKUP_DIR/networkman_db_$DATE.sql
gzip $BACKUP_DIR/networkman_db_$DATE.sql

# Backup files
tar -czf $BACKUP_DIR/files_$DATE.tar.gz /var/www/networkman

# Remove old backups (keep 30 days)
find $BACKUP_DIR -name "*.gz" -mtime +30 -delete

echo "Backup completed: $BACKUP_DIR/networkman_db_$DATE.sql.gz"
EOF

chmod +x /usr/local/bin/networkman-backup

# Add to crontab (daily backup at 2 AM)
(crontab -l 2>/dev/null; echo "0 2 * * * /usr/local/bin/networkman-backup > /dev/null 2>&1") | crontab -

log "Installation complete!"
echo ""
echo "========================================"
echo "🎉 NETWORKMAN INSTALLATION SUCCESSFUL!"
echo "========================================"
echo "🌐 Access URL: https://$DOMAIN"
echo "👤 Admin Username: admin"
echo "🔑 Admin Password: $ADMIN_PASS"
echo "🔐 License Key: $LICENSE_KEY"
echo ""
echo "⚠️  IMPORTANT:"
echo "1. Save the admin password above"
echo "2. Configure your NAS devices"
echo "3. Add your first users"
echo "4. Test the system thoroughly"
echo ""
echo "📚 Documentation: https://docs.networkman.startv.al"
echo "📧 Support: support@networkman.startv.al"
echo "========================================"