#!/bin/bash
# WHP Release Server Setup Script
# Sets up a complete release server for WHP distribution

# Exit on any error
set -e

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

# Configuration
RELEASE_DOMAIN="whp-releases.cloud-hosting.io"
WHP_REPO="gitea@repo.anhonesthost.net:cloud-hosting-platform/whp.git"
WEB_ROOT="/var/www/whp-releases"
WHP_DIR="/root/whp"

echo -e "${BLUE}=== WHP Release Server Setup ===${NC}"
echo "This script will configure a complete WHP release server"
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}Error: This script must be run as root${NC}"
    exit 1
fi

# Detect OS
if [ -f /etc/redhat-release ]; then
    OS="rhel"
    PACKAGE_MANAGER="dnf"
elif [ -f /etc/debian_version ]; then
    OS="debian"
    PACKAGE_MANAGER="apt"
else
    echo -e "${RED}Error: Unsupported operating system${NC}"
    exit 1
fi

echo -e "${GREEN}Detected OS: $OS${NC}"
echo ""

# Update system packages
echo -e "${YELLOW}Updating system packages...${NC}"
if [ "$OS" = "rhel" ]; then
    $PACKAGE_MANAGER update -y
    $PACKAGE_MANAGER install -y epel-release
elif [ "$OS" = "debian" ]; then
    $PACKAGE_MANAGER update
    $PACKAGE_MANAGER upgrade -y
fi

# Install required packages
echo -e "${YELLOW}Installing required packages...${NC}"
PACKAGES="httpd php git rsync tar curl wget openssl"

if [ "$OS" = "rhel" ]; then
    $PACKAGE_MANAGER install -y $PACKAGES mod_ssl
elif [ "$OS" = "debian" ]; then
    # Convert package names for Debian
    PACKAGES="apache2 php git rsync tar curl wget openssl libapache2-mod-php"
    $PACKAGE_MANAGER install -y $PACKAGES
fi

# Start and enable Apache
echo -e "${YELLOW}Configuring Apache web server...${NC}"
if [ "$OS" = "rhel" ]; then
    systemctl enable --now httpd
    APACHE_SERVICE="httpd"
    APACHE_CONFIG_DIR="/etc/httpd/conf.d"
    APACHE_LOG_DIR="/var/log/httpd"
elif [ "$OS" = "debian" ]; then
    systemctl enable --now apache2
    a2enmod rewrite
    a2enmod ssl
    APACHE_SERVICE="apache2"
    APACHE_CONFIG_DIR="/etc/apache2/sites-available"
    APACHE_LOG_DIR="/var/log/apache2"
fi

# Configure firewall (if firewalld is available)
if command -v firewall-cmd >/dev/null 2>&1; then
    echo -e "${YELLOW}Configuring firewall...${NC}"
    firewall-cmd --permanent --add-service=http
    firewall-cmd --permanent --add-service=https
    firewall-cmd --reload
fi

# Create web directory structure
echo -e "${YELLOW}Creating web directory structure...${NC}"
mkdir -p "$WEB_ROOT"/{releases,api}
mkdir -p "$APACHE_LOG_DIR"

# Clone WHP repository
echo -e "${YELLOW}Cloning WHP repository...${NC}"
if [ -d "$WHP_DIR" ]; then
    echo "Repository already exists, updating..."
    cd "$WHP_DIR"
    git pull
else
    # Add Git server to known_hosts
    if ! ssh-keygen -F repo.anhonesthost.net >/dev/null 2>&1; then
        echo "Adding Git server to known_hosts..."
        ssh-keyscan -H repo.anhonesthost.net >> ~/.ssh/known_hosts
    fi
    
    git clone "$WHP_REPO" "$WHP_DIR"
fi

# Copy release server files
echo -e "${YELLOW}Setting up release server files...${NC}"
cp -r "$WHP_DIR/release-server"/* "$WEB_ROOT/"

# Set proper permissions
if [ "$OS" = "rhel" ]; then
    chown -R apache:apache "$WEB_ROOT"
elif [ "$OS" = "debian" ]; then
    chown -R www-data:www-data "$WEB_ROOT"
fi

chmod 755 "$WEB_ROOT"
chmod 755 "$WEB_ROOT/releases"
find "$WEB_ROOT" -type f -exec chmod 644 {} \;

# Create Apache virtual host configuration
echo -e "${YELLOW}Creating Apache virtual host...${NC}"
if [ "$OS" = "rhel" ]; then
    cat > "$APACHE_CONFIG_DIR/whp-releases.conf" << EOF
<VirtualHost *:80>
    ServerName $RELEASE_DOMAIN
    ServerAlias $(hostname -I | awk '{print $1}')
    DocumentRoot $WEB_ROOT
    
    <Directory $WEB_ROOT>
        AllowOverride All
        Require all granted
        DirectoryIndex index.php
    </Directory>
    
    # Security headers
    Header always set X-Content-Type-Options nosniff
    Header always set X-Frame-Options DENY
    Header always set X-XSS-Protection "1; mode=block"
    
    ErrorLog $APACHE_LOG_DIR/whp-releases-error.log
    CustomLog $APACHE_LOG_DIR/whp-releases-access.log combined
</VirtualHost>
EOF
elif [ "$OS" = "debian" ]; then
    cat > "$APACHE_CONFIG_DIR/whp-releases.conf" << EOF
<VirtualHost *:80>
    ServerName $RELEASE_DOMAIN
    ServerAlias $(hostname -I | awk '{print $1}')
    DocumentRoot $WEB_ROOT
    
    <Directory $WEB_ROOT>
        AllowOverride All
        Require all granted
        DirectoryIndex index.php
    </Directory>
    
    # Security headers
    Header always set X-Content-Type-Options nosniff
    Header always set X-Frame-Options DENY
    Header always set X-XSS-Protection "1; mode=block"
    
    ErrorLog $APACHE_LOG_DIR/whp-releases-error.log
    CustomLog $APACHE_LOG_DIR/whp-releases-access.log combined
</VirtualHost>
EOF
    
    a2ensite whp-releases
fi

# Test Apache configuration
echo -e "${YELLOW}Testing Apache configuration...${NC}"
if [ "$OS" = "rhel" ]; then
    httpd -t
elif [ "$OS" = "debian" ]; then
    apache2ctl configtest
fi

# Restart Apache
echo -e "${YELLOW}Restarting Apache...${NC}"
systemctl reload $APACHE_SERVICE

# Make build script executable
chmod +x "$WHP_DIR/scripts/build-release.sh"

# Create initial release
echo -e "${YELLOW}Creating initial release...${NC}"
cd "$WHP_DIR"
if ./scripts/build-release.sh; then
    echo -e "${GREEN}Initial release created successfully${NC}"
else
    echo -e "${RED}Warning: Failed to create initial release${NC}"
    echo "You may need to run './scripts/build-release.sh' manually later"
fi

# Set up log rotation
echo -e "${YELLOW}Setting up log rotation...${NC}"
cat > /etc/logrotate.d/whp-releases << EOF
$APACHE_LOG_DIR/whp-releases-*.log {
    daily
    missingok
    rotate 52
    compress
    delaycompress
    notifempty
    create 644 apache apache
    postrotate
        systemctl reload $APACHE_SERVICE > /dev/null 2>&1 || true
    endscript
}
EOF

# Create maintenance scripts
echo -e "${YELLOW}Creating maintenance scripts...${NC}"
mkdir -p /opt/whp-release-server

# Create update script
cat > /opt/whp-release-server/update-release-server.sh << 'EOF'
#!/bin/bash
# Update release server from repository

set -e

WHP_DIR="/root/whp"
WEB_ROOT="/var/www/whp-releases"

echo "Updating WHP release server..."

# Update repository
cd "$WHP_DIR"
git pull

# Update web files
cp -r "$WHP_DIR/release-server"/* "$WEB_ROOT/"

# Fix permissions
if [ -f /etc/redhat-release ]; then
    chown -R apache:apache "$WEB_ROOT"
else
    chown -R www-data:www-data "$WEB_ROOT"
fi

echo "Release server updated successfully"
EOF

# Create build and deploy script
cat > /opt/whp-release-server/build-and-deploy.sh << 'EOF'
#!/bin/bash
# Build and deploy new WHP release

set -e

WHP_DIR="/root/whp"

echo "Building and deploying new WHP release..."

# Update repository
cd "$WHP_DIR"
git pull

# Build new release
./scripts/build-release.sh

echo "New release built and deployed successfully"
EOF

# Make scripts executable
chmod +x /opt/whp-release-server/*.sh

# Create systemd timer for automatic repository updates (optional)
echo -e "${YELLOW}Setting up automatic updates (optional)...${NC}"
cat > /etc/systemd/system/whp-release-update.service << EOF
[Unit]
Description=Update WHP Release Server
After=network.target

[Service]
Type=oneshot
ExecStart=/opt/whp-release-server/update-release-server.sh
User=root
EOF

cat > /etc/systemd/system/whp-release-update.timer << EOF
[Unit]
Description=Update WHP Release Server Daily
Requires=whp-release-update.service

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target
EOF

systemctl daemon-reload
systemctl enable whp-release-update.timer
systemctl start whp-release-update.timer

# Test the setup
echo -e "${YELLOW}Testing release server setup...${NC}"
sleep 2

# Test main page
if curl -sf http://localhost/ >/dev/null; then
    echo -e "${GREEN}✓ Main page accessible${NC}"
else
    echo -e "${RED}✗ Main page not accessible${NC}"
fi

# Test API
if curl -sf "http://localhost/api/check.php?version=2025.01.1" >/dev/null; then
    echo -e "${GREEN}✓ API endpoint accessible${NC}"
else
    echo -e "${RED}✗ API endpoint not accessible${NC}"
fi

# Test releases directory
if [ -d "$WEB_ROOT/releases" ] && [ -r "$WEB_ROOT/releases" ]; then
    echo -e "${GREEN}✓ Releases directory accessible${NC}"
else
    echo -e "${RED}✗ Releases directory not accessible${NC}"
fi

# Generate SSL certificate (Let's Encrypt)
echo ""
echo -e "${YELLOW}SSL Certificate Setup${NC}"
echo "To set up SSL with Let's Encrypt, run:"
echo "  dnf install -y certbot python3-certbot-apache"
echo "  certbot --apache -d $RELEASE_DOMAIN"
echo ""

# Display final information
echo -e "${GREEN}=== WHP Release Server Setup Complete ===${NC}"
echo ""
echo "Server Information:"
echo "  Domain: $RELEASE_DOMAIN"
echo "  Web Root: $WEB_ROOT"
echo "  Repository: $WHP_DIR"
echo ""
echo "Available URLs:"
echo "  Main Page: http://$RELEASE_DOMAIN/"
echo "  API Check: http://$RELEASE_DOMAIN/api/check.php?version=2025.01.1"
echo "  Releases: http://$RELEASE_DOMAIN/releases/"
echo ""
echo "Maintenance Commands:"
echo "  Update server: /opt/whp-release-server/update-release-server.sh"
echo "  Build release: /opt/whp-release-server/build-and-deploy.sh"
echo "  Manual build: cd $WHP_DIR && ./scripts/build-release.sh"
echo ""
echo "Log Files:"
echo "  Access: $APACHE_LOG_DIR/whp-releases-access.log"
echo "  Error: $APACHE_LOG_DIR/whp-releases-error.log"
echo ""
echo -e "${YELLOW}Next Steps:${NC}"
echo "1. Configure DNS to point $RELEASE_DOMAIN to this server"
echo "2. Set up SSL certificate with Let's Encrypt"
echo "3. Test the release server from external networks"
echo "4. Set up monitoring and backups"
echo ""
echo -e "${GREEN}Release server is ready for use!${NC}"