(Created page with "thumb|'''ShellScripting''' Buat file baru dengan nama konfig_apache.sh<syntaxhighlight lang="linuxconfig"> nano konfig_apache.sh </syntaxhighlight>isikan script berikut ini :<syntaxhighlight lang="linuxconfig" line="1"> #!/bin/bash # ============================================== # AUTO WEB SERVER SETUP SCRIPT # Debian 12 - Apache + PHP + Virtual Host # ============================================== # Colors for output RED='\033[0;31m' GREEN=...")
 
No edit summary
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
[[File:ShellScripting.png|thumb|'''ShellScripting''']]
[[File:ShellScripting.png|thumb|'''ShellScripting''']]
Buat file baru dengan nama konfig_apache.sh<syntaxhighlight lang="linuxconfig">
Buat file baru dengan nama konfig_apache.sh<syntaxhighlight lang="linuxconfig">
nano konfig_apache.sh
nano cleanup.sh
</syntaxhighlight>isikan script berikut ini :<syntaxhighlight lang="linuxconfig" line="1">
</syntaxhighlight>isikan script berikut ini :<syntaxhighlight lang="linuxconfig" line="1">
#!/bin/bash
#!/bin/bash
# ==============================================
# ==============================================
# AUTO WEB SERVER SETUP SCRIPT
# SMART DEBIAN CLEANUP SCRIPT
# Debian 12 - Apache + PHP + Virtual Host
# Hanya hapus package non-essential, keep system packages
# ==============================================
# ==============================================


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


# Function to print colored output
print_status() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_status() {
print_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
    echo -e "${BLUE}[INFO]${NC} $1"
print_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
}
print_error() { echo -e "${RED}[ERROR]${NC} $1"; }
 
print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}
 
print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}
 
print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}


# Check if running as root
# Check if running as root
Line 39: Line 27:
fi
fi


# Banner
# Essential packages yang TIDAK BOLEH dihapus
echo "=========================================="
ESSENTIAL_PACKAGES=(
echo "   AUTO WEB SERVER SETUP SCRIPT"
    # System Base
echo "     Apache + PHP + Virtual Host"
    "apt" "base-files" "base-passwd" "bash" "bsdutils" "coreutils" "dash" "debconf"
echo "=========================================="
    "debian-archive-keyring" "debianutils" "diffutils" "dpkg" "e2fsprogs" "findutils"
    "gawk" "grep" "gzip" "hostname" "init" "libc6" "login" "mount" "ncurses-base"
    "ncurses-bin" "perl-base" "procps" "sed" "sysvinit-utils" "tar" "util-linux"
   
    # Network Essential
    "iproute2" "iputils-ping" "netbase" "netcat-openbsd" "openssh-client" "openssh-server"
    "wget" "curl"
   
    # System Management
    "systemd" "systemd-sysv" "udev" "sudo" "adduser" "passwd"
   
    # Hardware
    "linux-image-amd64" "fdisk" "grub-common" "grub-pc" "grub2-common"
   
    # Security
    "apt-transport-https" "ca-certificates" "gnupg" "gnupg2"
   
    # File Systems
    "e2fsprogs" "dosfstools" "mount" "util-linux"
   
    # Shell & Tools
    "vim-common" "nano" "less" "man-db" "manpages"
)
 
# Services packages yang BOLEH dihapus (non-essential) - DIPERBARUI
SERVICE_PACKAGES=(
    # Web Servers
    "apache2" "nginx" "lighttpd"
   
    # Database Servers
    "mariadb-server" "mariadb-client" "mysql-server" "mysql-client"
   
    # DNS Server
    "bind9" "bind9utils" "bind9-doc"
   
    # Mail Servers
    "postfix" "dovecot-imapd" "dovecot-pop3d"
   
    # FTP Servers
    "vsftpd" "proftpd"
   
    # Programming Languages & Frameworks - DITAMBAHKAN
    "php" "php-common" "php-cli" "php-fpm" "php-mysql" "php-curl" "php-gd" "php-mbstring"
    "php-xml" "php-zip" "php-bcmath" "php-json" "php-imagick" "php-redis"
    "phpmyadmin"
   
    # Python & Tools
    "python3" "python2" "python3-pip" "python3-venv"
    "perl" "ruby"
   
    # Development Tools
    "build-essential" "git" "nodejs" "npm"
   
    # Other Services
    "postgresql" "mongodb" "redis-server" "memcached"
)
 
# Banner dengan warning
echo ""
echo -e "${YELLOW}==========================================${NC}"
echo -e "${YELLOW}        SMART DEBIAN CLEANUP SCRIPT${NC}"
echo -e "${YELLOW}    Hapus Non-Essential Packages Only${NC}"
echo -e "${YELLOW}==========================================${NC}"
echo ""
echo -e "${YELLOW}SCRIPT INI AKAN:${NC}"
echo -e "${YELLOW}• Hapus package services (Apache, MySQL, PHP, DNS, dll)${NC}"
echo -e "${YELLOW}• Hapus config files services${NC}"
echo -e "${YELLOW}• Hapus data services${NC}"
echo -e "${YELLOW}• Membersihkan cache dan log${NC}"
echo ""
echo -e "${YELLOW}YANG AKAN DIPERTAHANKAN:${NC}"
echo -e "${GREEN}• Semua system essential packages${NC}"
echo -e "${GREEN}• Network configuration${NC}"
echo -e "${GREEN}• User accounts dan home directories${NC}"
echo ""
echo ""


# Step 1: System Update
# Confirmation
print_status "Step 1: Update system packages..."
read -p "Lanjutkan dengan cleanup? (y/N): " confirm
apt update && apt upgrade -y
if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
print_success "System update completed"
    print_error "Script dibatalkan!"
    exit 1
fi


# Step 2: Install Apache
# Function untuk cek apakah package installed
print_status "Step 2: Installing Apache Web Server..."
is_installed() {
apt install -y apache2 apache2-utils
    dpkg -l "$1" 2>/dev/null | grep -q "^ii"
print_success "Apache installed successfully"
}


# Step 3: Install PHP and Extensions
print_status "Memulai SMART Debian Cleanup..."
print_status "Step 3: Installing PHP and extensions..."
echo "=========================================="
apt install -y php php-cli php-fpm php-json php-common php-mysql php-zip php-gd php-mbstring php-curl php-xml php-bcmath php-json php-intl


# Install additional PHP extensions for web development
# Step 1: Analyze System
apt install -y php-gd php-imagick php-redis php-memcached php-xdebug
print_status "Step 1: Menganalisa system..."
print_success "PHP and extensions installed successfully"


# Step 4: Enable Apache Modules
# Get installed services packages
print_status "Step 4: Enabling Apache modules..."
print_status "Mendeteksi installed services..."
a2enmod rewrite
installed_services=()
a2enmod ssl
for service in "${SERVICE_PACKAGES[@]}"; do
a2enmod headers
    if is_installed "$service"; then
print_success "Apache modules enabled"
        installed_services+=("$service")
    fi
done


# Step 5: Create Main Web Directory
# Deteksi PHP packages secara khusus
print_status "Step 5: Setting up web directory..."
print_status "Mendeteksi PHP packages..."
mkdir -p /var/www/html
php_packages=$(dpkg -l | grep -E "^ii.*php" | awk '{print $2}' | tr '\n' ' ')
chown -R www-data:www-data /var/www/html
if [ -n "$php_packages" ]; then
chmod -R 755 /var/www/html
    print_status "PHP packages terdeteksi: $php_packages"
print_success "Web directory configured"
fi


# Step 6: Get Domain Name for Virtual Host
# Show analysis results
echo ""
echo ""
print_status "Step 6: Virtual Host Configuration"
print_status "ANALYSIS RESULTS:"
read -p "Masukkan nama domain untuk virtual host (contoh: mysite.local): " domain_name
echo "-------------------"
echo "• Total services packages: ${#installed_services[@]}"
echo "• PHP packages: $(echo "$php_packages" | wc -w)"
echo "• Essential packages: ${#ESSENTIAL_PACKAGES[@]}"
 
if [ ${#installed_services[@]} -eq 0 ]; then
    print_success "Tidak ada services packages yang terdeteksi!"
    echo "Tidak ada yang perlu dibersihkan."
    exit 0
fi


if [ -z "$domain_name" ]; then
echo ""
     print_error "Domain name tidak boleh kosong!"
print_status "Services yang akan dihapus:"
for service in "${installed_services[@]}"; do
    echo "  - $service"
done
 
# Final confirmation
echo ""
read -p "Hapus services di atas? (y/N): " final_confirm
if [ "$final_confirm" != "y" ] && [ "$final_confirm" != "Y" ]; then
     print_error "Cleanup dibatalkan!"
     exit 1
     exit 1
fi
fi


# Step 7: Create Virtual Host Configuration
# Step 2: Stop Services
print_status "Membuat virtual host untuk: $domain_name"
print_status "Step 2: Menghentikan services..."
 
for service in "${installed_services[@]}"; do
    case $service in
        apache2|nginx)
            systemctl stop apache2 2>/dev/null || true
            systemctl stop nginx 2>/dev/null || true
            ;;
        mariadb-server|mysql-server)
            systemctl stop mariadb 2>/dev/null || true
            systemctl stop mysql 2>/dev/null || true
            ;;
        bind9)
            systemctl stop bind9 2>/dev/null || true
            ;;
        postfix|dovecot*)
            systemctl stop postfix 2>/dev/null || true
            systemctl stop dovecot 2>/dev/null || true
            ;;
        vsftpd|proftpd)
            systemctl stop vsftpd 2>/dev/null || true
            systemctl stop proftpd 2>/dev/null || true
            ;;
        php*-fpm)
            systemctl stop php8.2-fpm 2>/dev/null || true
            systemctl stop php8.1-fpm 2>/dev/null || true
            systemctl stop php8.0-fpm 2>/dev/null || true
            systemctl stop php7.4-fpm 2>/dev/null || true
            ;;
        postgresql)
            systemctl stop postgresql 2>/dev/null || true
            ;;
        redis-server)
            systemctl stop redis-server 2>/dev/null || true
            ;;
        memcached)
            systemctl stop memcached 2>/dev/null || true
            ;;
    esac
done
 
print_success "Services stopped"
 
# Step 3: Remove Service Packages
print_status "Step 3: Menghapus service packages..."
 
for service in "${installed_services[@]}"; do
    print_status "Menghapus: $service"
    apt remove --purge -y "$service" 2>/dev/null || true
done
 
# Additional: Remove PHP packages yang mungkin terlewat
print_status "Menghapus PHP packages tambahan..."
php_related_packages=$(dpkg -l | grep -E "^ii.*php" | awk '{print $2}')
for php_pkg in $php_related_packages; do
    if [[ " ${SERVICE_PACKAGES[@]} " =~ " ${php_pkg} " ]]; then
        continue  # Sudah dihapus di loop utama
    else
        print_status "Menghapus PHP package: $php_pkg"
        apt remove --purge -y "$php_pkg" 2>/dev/null || true
    fi
done
 
print_success "Service packages removed"
 
# Step 4: Remove Service Data and Configs
print_status "Step 4: Membersihkan data dan config services..."
 
# Web Servers
if [ -d "/etc/apache2" ]; then
    rm -rf /etc/apache2
    print_status "Apache config dihapus"
fi
 
if [ -d "/etc/nginx" ]; then
    rm -rf /etc/nginx
    print_status "Nginx config dihapus"
fi
 
if [ -d "/var/www" ]; then
    # Hanya hapus content, bukan directory structure
    rm -rf /var/www/html/*
    rm -rf /var/www/*/
    print_status "Web content dibersihkan"
fi
 
# Database Servers
if [ -d "/var/lib/mysql" ]; then
    rm -rf /var/lib/mysql/*
    print_status "MySQL data dibersihkan"
fi
 
if [ -d "/etc/mysql" ]; then
    rm -rf /etc/mysql
    print_status "MySQL config dihapus"
fi
 
# PHP Configs
if [ -d "/etc/php" ]; then
    rm -rf /etc/php
    print_status "PHP config dihapus"
fi
 
# DNS Server
if [ -d "/etc/bind" ]; then
    rm -rf /etc/bind
    print_status "BIND config dihapus"
fi
 
if [ -d "/var/cache/bind" ]; then
    rm -rf /var/cache/bind/*
    print_status "BIND cache dibersihkan"
fi
 
# Mail Servers
if [ -d "/etc/postfix" ]; then
    rm -rf /etc/postfix
    print_status "Postfix config dihapus"
fi
 
if [ -d "/etc/dovecot" ]; then
    rm -rf /etc/dovecot
    print_status "Dovecot config dihapus"
fi
 
# FTP Servers
if [ -d "/etc/vsftpd" ]; then
    rm -rf /etc/vsftpd
    print_status "VSFTPD config dihapus"
fi
 
if [ -d "/etc/proftpd" ]; then
    rm -rf /etc/proftpd
    print_status "ProFTPD config dihapus"
fi


VHOST_CONF="/etc/apache2/sites-available/${domain_name}.conf"
# Other Databases
if [ -d "/var/lib/postgresql" ]; then
    rm -rf /var/lib/postgresql/*
    print_status "PostgreSQL data dibersihkan"
fi


cat > "$VHOST_CONF" << EOF
if [ -d "/etc/postgresql" ]; then
<VirtualHost *:80>
    rm -rf /etc/postgresql
     ServerName $domain_name
     print_status "PostgreSQL config dihapus"
    ServerAlias www.$domain_name
fi
    ServerAdmin webmaster@$domain_name
 
     DocumentRoot /var/www/$domain_name
# Redis
      
if [ -d "/var/lib/redis" ]; then
    ErrorLog \${APACHE_LOG_DIR}/$domain_name_error.log
     rm -rf /var/lib/redis/*
    CustomLog \${APACHE_LOG_DIR}/$domain_name_access.log combined
     print_status "Redis data dibersihkan"
      
fi
    <Directory /var/www/$domain_name>
 
        Options Indexes FollowSymLinks MultiViews
if [ -d "/etc/redis" ]; then
        AllowOverride All
     rm -rf /etc/redis
        Order allow,deny
    print_status "Redis config dihapus"
        allow from all
fi
        Require all granted
 
    </Directory>
print_success "Service data and configs cleaned"
</VirtualHost>
 
EOF
# Step 5: Clean Service Logs
print_status "Step 5: Membersihkan service logs..."


print_success "Virtual host configuration created: $VHOST_CONF"
service_logs=(
    "/var/log/apache2"
    "/var/log/nginx"
    "/var/log/mysql"
    "/var/log/mariadb"
    "/var/log/bind9"
    "/var/log/postfix"
    "/var/log/dovecot"
    "/var/log/vsftpd"
    "/var/log/php"
    "/var/log/postgresql"
    "/var/log/redis"
)


# Step 8: Create Web Directory for Domain
for log_dir in "${service_logs[@]}"; do
print_status "Membuat web directory untuk $domain_name..."
    if [ -d "$log_dir" ]; then
mkdir -p "/var/www/$domain_name"
        rm -rf "$log_dir"/*
chown -R www-data:www-data "/var/www/$domain_name"
        print_status "Logs cleaned: $(basename "$log_dir")"
chmod -R 755 "/var/www/$domain_name"
    fi
done


# Step 9: Create Custom Index Page
print_success "Service logs cleaned"
print_status "Membuat file index.html custom..."


cat > "/var/www/$domain_name/index.html" << EOF
# Step 6: Clean Package Cache
<!DOCTYPE html>
print_status "Step 6: Membersihkan package cache..."
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Selamat Datang di $domain_name</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .jumbotron {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 4rem 2rem;
            margin-top: 2rem;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        .feature-icon {
            font-size: 3rem;
            margin-bottom: 1rem;
        }
        .tech-badge {
            font-size: 0.9rem;
            margin: 0.2rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="jumbotron text-center">
            <h1 class="display-4">🎉 Selamat Datang!</h1>
            <p class="lead">Website <strong>$domain_name</strong> berhasil diaktifkan</p>
            <hr class="my-4">
            <p>Server Anda sekarang berjalan dengan:</p>
           
            <div class="row mt-4">
                <div class="col-md-3">
                    <div class="feature-icon">🌐</div>
                    <h5>Apache2</h5>
                    <p>Web Server</p>
                </div>
                <div class="col-md-3">
                    <div class="feature-icon">🐘</div>
                    <h5>PHP 8.2</h5>
                    <p>Processing</p>
                </div>
                <div class="col-md-3">
                    <div class="feature-icon">📁</div>
                    <h5>Virtual Host</h5>
                    <p>Domain: $domain_name</p>
                </div>
                <div class="col-md-3">
                    <div class="feature-icon">⚡</div>
                    <h5>Optimized</h5>
                    <p>Ready to Code</p>
                </div>
            </div>
           
            <div class="mt-4">
                <span class="badge tech-badge bg-primary">Apache 2.4</span>
                <span class="badge tech-badge bg-success">PHP 8.2</span>
                <span class="badge tech-badge bg-warning">Debian 12</span>
                <span class="badge tech-badge bg-info">Bootstrap 5</span>
                <span class="badge tech-badge bg-dark">Shell Script</span>
            </div>
           
            <div class="mt-4">
                <a href="/info.php" class="btn btn-light btn-lg">🔧 PHP Info</a>
                <a href="/" class="btn btn-outline-light btn-lg">🔄 Refresh</a>
            </div>
        </div>
       
        <div class="row mt-5">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">📊 Server Information</h5>
                        <p class="card-text">
                            <strong>Domain:</strong> $domain_name<br>
                            <strong>Directory:</strong> /var/www/$domain_name<br>
                            <strong>Config:</strong> /etc/apache2/sites-available/$domain_name.conf<br>
                            <strong>Time:</strong> $(date)
                        </p>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">🚀 Next Steps</h5>
                        <p class="card-text">
                            • Upload file website Anda<br>
                            • Setup database MySQL<br>
                            • Configure SSL certificate<br>
                            • Monitor server logs<br>
                            • Enjoy coding! 🎯
                        </p>
                    </div>
                </div>
            </div>
        </div>
       
        <footer class="text-center mt-5 mb-3">
            <p class="text-muted">Auto-generated by Apache Setup Script | Debian 12</p>
        </footer>
    </div>
   
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
EOF


print_success "Custom index.html created"
apt autoremove -y
apt autoclean
apt clean


# Step 10: Create PHP Info File
print_success "Package cache cleaned"
print_status "Membuat file info.php untuk testing..."


cat > "/var/www/$domain_name/info.php" << EOF
# Step 7: Clean Temporary Files
<?php
print_status "Step 7: Membersihkan temporary files..."
phpinfo();
?>
EOF


print_success "PHP info file created"
# Clean temp directories
rm -rf /tmp/*
rm -rf /var/tmp/*


# Step 11: Enable Virtual Host
# Clean package cache
print_status "Step 7: Mengaktifkan virtual host..."
rm -rf /var/cache/apt/archives/*
a2ensite $domain_name.conf
rm -rf /var/cache/apt/archives/partial/*


# Step 12: Disable default site (optional)
# Clean PHP sessions and cache
print_status "Menonaktifkan default site..."
if [ -d "/var/lib/php/sessions" ]; then
a2dissite 000-default.conf
    rm -rf /var/lib/php/sessions/*
    print_status "PHP sessions dibersihkan"
fi


# Step 13: Restart Apache
# Clean old logs (keep current)
print_status "Restarting Apache service..."
find /var/log -name "*.log" -type f -exec truncate -s 0 {} \; 2>/dev/null || true
systemctl restart apache2
find /var/log -name "*.gz" -type f -delete 2>/dev/null || true
find /var/log -name "*.1" -type f -delete 2>/dev/null || true


# Step 14: Add to hosts file for local testing
print_success "Temporary files cleaned"
print_status "Menambahkan entry ke /etc/hosts..."
echo "127.0.0.1    $domain_name" >> /etc/hosts
echo "127.0.0.1    www.$domain_name" >> /etc/hosts


print_success "Hosts file updated"
# Step 8: Final Check
print_status "Step 8: Final system check..."


# Step 15: Final Summary
# Cek apakah PHP masih ada
if dpkg -l | grep -q "^ii.*php"; then
    remaining_php=$(dpkg -l | grep "^ii.*php" | awk '{print $2}' | tr '\n' ' ')
    print_warning "Masih ada PHP packages: $remaining_php"
else
    print_success "Semua PHP packages berhasil dihapus"
fi
 
# Cek essential packages masih ada
essential_ok=true
for essential in "${ESSENTIAL_PACKAGES[@]}"; do
    if is_installed "$essential"; then
        continue
    else
        print_warning "Essential package missing: $essential"
        essential_ok=false
    fi
done
 
if $essential_ok; then
    print_success "Semua essential packages terinstall dengan baik"
else
    print_warning "Beberapa essential packages mungkin hilang"
fi
 
# Final Summary
echo ""
echo ""
echo "=========================================="
echo "=========================================="
print_success "WEB SERVER SETUP COMPLETED!"
print_success "SMART DEBIAN CLEANUP COMPLETED!"
echo "=========================================="
echo "=========================================="
echo ""
echo ""
echo "📋 SUMMARY:"
echo "📋 YANG SUDAH DIBERSIHKAN:"
echo "-----------"
echo "--------------------------"
echo "• 🌐 Domain: $domain_name"
echo "✅ Service packages: ${#installed_services[@]} packages"
echo "• 📁 Web Directory: /var/www/$domain_name"
echo "✅ PHP packages: $(echo "$php_packages" | wc -w) packages"
echo "• ⚙️  Config File: /etc/apache2/sites-available/$domain_name.conf"
echo "✅ Service config files"
echo "• 🐘 PHP Version: $(php -v | head -n1)"
echo "✅ Service data directories"  
echo "• 🔥 Apache Status: $(systemctl is-active apache2)"
echo "✅ Service log files"
echo "✅ Package cache"
echo "✅ Temporary files"
echo ""
echo ""
echo "🚀 TEST YOUR SETUP:"
echo "🔒 YANG DIPERTAHANKAN:"
echo "------------------"
echo "---------------------"
echo "1. Browser: http://$domain_name"
echo "${#ESSENTIAL_PACKAGES[@]} essential packages"
echo "2. PHP Info: http://$domain_name/info.php"
echo "✅ System base configuration"
echo "✅ User accounts dan home directories"
echo "✅ Network settings"
echo "✅ System logs (current)"
echo ""
echo ""
echo "📝 NEXT COMMANDS:"
echo "🚀 SISTEM BERSIH DAN SIAP UNTUK INSTALL BARU!"
echo "----------------"
echo "• Edit website: nano /var/www/$domain_name/index.html"
echo "• View logs: tail -f /var/log/apache2/${domain_name}_error.log"
echo "• Add SSL: certbot --apache -d $domain_name"
echo ""
echo "🎉 SELAMAT! Web server Anda sudah aktif dan siap digunakan!"
echo "=========================================="
echo "=========================================="


# Step 16: Test PHP (optional)
# Recommendations
print_status "Testing PHP configuration..."
echo ""
php -v > /dev/null 2>&1
print_status "REKOMENDASI SELANJUTNYA:"
if [ $? -eq 0 ]; then
echo "• Install services yang diperlukan:"
    print_success "PHP is working correctly"
echo "  apt install apache2 mariadb-server php phpmyadmin"
else
echo "• Untuk development PHP:"
    print_warning "PHP mungkin ada masalah, cek dengan: php -v"
echo " apt install php php-cli php-mysql php-curl php-gd php-mbstring php-xml php-zip"
fi
echo "• Cek system health:"
 
echo " systemctl status"
# Step 17: Show service status
echo "  df -h"
print_status "Apache service status:"
echo "  free -h"
systemctl status apache2 --no-pager -l
echo ""
print_success "Cleanup selesai! System dalam keadaan bersih dan stabil!"
</syntaxhighlight>Simpan script tersebut.
</syntaxhighlight>Simpan script tersebut.


beri hak akses eksekusi<syntaxhighlight lang="linuxconfig">
beri hak akses eksekusi<syntaxhighlight lang="linuxconfig">
chmod +x konfig_apache.sh
chmod +x cleanup.sh
</syntaxhighlight>Jika script tidak jalan, jalankan perintah berikut<syntaxhighlight lang="linuxconfig">
sed -i 's/\r$//' cleanup.sh
</syntaxhighlight>jalankan script<syntaxhighlight lang="linuxconfig">
</syntaxhighlight>jalankan script<syntaxhighlight lang="linuxconfig">
./konfig_apache.sh
./cleanup.sh
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 18:06, 8 October 2025

ShellScripting

Buat file baru dengan nama konfig_apache.sh

nano cleanup.sh

isikan script berikut ini :

#!/bin/bash
# ==============================================
# SMART DEBIAN CLEANUP SCRIPT
# Hanya hapus package non-essential, keep system packages
# ==============================================

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

print_status() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
print_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    print_error "Script harus dijalankan dengan sudo!"
    exit 1
fi

# Essential packages yang TIDAK BOLEH dihapus
ESSENTIAL_PACKAGES=(
    # System Base
    "apt" "base-files" "base-passwd" "bash" "bsdutils" "coreutils" "dash" "debconf" 
    "debian-archive-keyring" "debianutils" "diffutils" "dpkg" "e2fsprogs" "findutils"
    "gawk" "grep" "gzip" "hostname" "init" "libc6" "login" "mount" "ncurses-base"
    "ncurses-bin" "perl-base" "procps" "sed" "sysvinit-utils" "tar" "util-linux"
    
    # Network Essential
    "iproute2" "iputils-ping" "netbase" "netcat-openbsd" "openssh-client" "openssh-server"
    "wget" "curl"
    
    # System Management
    "systemd" "systemd-sysv" "udev" "sudo" "adduser" "passwd"
    
    # Hardware
    "linux-image-amd64" "fdisk" "grub-common" "grub-pc" "grub2-common"
    
    # Security
    "apt-transport-https" "ca-certificates" "gnupg" "gnupg2"
    
    # File Systems
    "e2fsprogs" "dosfstools" "mount" "util-linux"
    
    # Shell & Tools
    "vim-common" "nano" "less" "man-db" "manpages"
)

# Services packages yang BOLEH dihapus (non-essential) - DIPERBARUI
SERVICE_PACKAGES=(
    # Web Servers
    "apache2" "nginx" "lighttpd"
    
    # Database Servers
    "mariadb-server" "mariadb-client" "mysql-server" "mysql-client"
    
    # DNS Server
    "bind9" "bind9utils" "bind9-doc"
    
    # Mail Servers
    "postfix" "dovecot-imapd" "dovecot-pop3d"
    
    # FTP Servers
    "vsftpd" "proftpd"
    
    # Programming Languages & Frameworks - DITAMBAHKAN
    "php" "php-common" "php-cli" "php-fpm" "php-mysql" "php-curl" "php-gd" "php-mbstring"
    "php-xml" "php-zip" "php-bcmath" "php-json" "php-imagick" "php-redis"
    "phpmyadmin"
    
    # Python & Tools
    "python3" "python2" "python3-pip" "python3-venv"
    "perl" "ruby"
    
    # Development Tools
    "build-essential" "git" "nodejs" "npm"
    
    # Other Services
    "postgresql" "mongodb" "redis-server" "memcached"
)

# Banner dengan warning
echo ""
echo -e "${YELLOW}==========================================${NC}"
echo -e "${YELLOW}        SMART DEBIAN CLEANUP SCRIPT${NC}"
echo -e "${YELLOW}     Hapus Non-Essential Packages Only${NC}"
echo -e "${YELLOW}==========================================${NC}"
echo ""
echo -e "${YELLOW}SCRIPT INI AKAN:${NC}"
echo -e "${YELLOW}• Hapus package services (Apache, MySQL, PHP, DNS, dll)${NC}"
echo -e "${YELLOW}• Hapus config files services${NC}"
echo -e "${YELLOW}• Hapus data services${NC}"
echo -e "${YELLOW}• Membersihkan cache dan log${NC}"
echo ""
echo -e "${YELLOW}YANG AKAN DIPERTAHANKAN:${NC}"
echo -e "${GREEN}• Semua system essential packages${NC}"
echo -e "${GREEN}• Network configuration${NC}"
echo -e "${GREEN}• User accounts dan home directories${NC}"
echo ""

# Confirmation
read -p "Lanjutkan dengan cleanup? (y/N): " confirm
if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
    print_error "Script dibatalkan!"
    exit 1
fi

# Function untuk cek apakah package installed
is_installed() {
    dpkg -l "$1" 2>/dev/null | grep -q "^ii"
}

print_status "Memulai SMART Debian Cleanup..."
echo "=========================================="

# Step 1: Analyze System
print_status "Step 1: Menganalisa system..."

# Get installed services packages
print_status "Mendeteksi installed services..."
installed_services=()
for service in "${SERVICE_PACKAGES[@]}"; do
    if is_installed "$service"; then
        installed_services+=("$service")
    fi
done

# Deteksi PHP packages secara khusus
print_status "Mendeteksi PHP packages..."
php_packages=$(dpkg -l | grep -E "^ii.*php" | awk '{print $2}' | tr '\n' ' ')
if [ -n "$php_packages" ]; then
    print_status "PHP packages terdeteksi: $php_packages"
fi

# Show analysis results
echo ""
print_status "ANALYSIS RESULTS:"
echo "-------------------"
echo "• Total services packages: ${#installed_services[@]}"
echo "• PHP packages: $(echo "$php_packages" | wc -w)"
echo "• Essential packages: ${#ESSENTIAL_PACKAGES[@]}"

if [ ${#installed_services[@]} -eq 0 ]; then
    print_success "Tidak ada services packages yang terdeteksi!"
    echo "Tidak ada yang perlu dibersihkan."
    exit 0
fi

echo ""
print_status "Services yang akan dihapus:"
for service in "${installed_services[@]}"; do
    echo "  - $service"
done

# Final confirmation
echo ""
read -p "Hapus services di atas? (y/N): " final_confirm
if [ "$final_confirm" != "y" ] && [ "$final_confirm" != "Y" ]; then
    print_error "Cleanup dibatalkan!"
    exit 1
fi

# Step 2: Stop Services
print_status "Step 2: Menghentikan services..."

for service in "${installed_services[@]}"; do
    case $service in
        apache2|nginx)
            systemctl stop apache2 2>/dev/null || true
            systemctl stop nginx 2>/dev/null || true
            ;;
        mariadb-server|mysql-server)
            systemctl stop mariadb 2>/dev/null || true
            systemctl stop mysql 2>/dev/null || true
            ;;
        bind9)
            systemctl stop bind9 2>/dev/null || true
            ;;
        postfix|dovecot*)
            systemctl stop postfix 2>/dev/null || true
            systemctl stop dovecot 2>/dev/null || true
            ;;
        vsftpd|proftpd)
            systemctl stop vsftpd 2>/dev/null || true
            systemctl stop proftpd 2>/dev/null || true
            ;;
        php*-fpm)
            systemctl stop php8.2-fpm 2>/dev/null || true
            systemctl stop php8.1-fpm 2>/dev/null || true
            systemctl stop php8.0-fpm 2>/dev/null || true
            systemctl stop php7.4-fpm 2>/dev/null || true
            ;;
        postgresql)
            systemctl stop postgresql 2>/dev/null || true
            ;;
        redis-server)
            systemctl stop redis-server 2>/dev/null || true
            ;;
        memcached)
            systemctl stop memcached 2>/dev/null || true
            ;;
    esac
done

print_success "Services stopped"

# Step 3: Remove Service Packages
print_status "Step 3: Menghapus service packages..."

for service in "${installed_services[@]}"; do
    print_status "Menghapus: $service"
    apt remove --purge -y "$service" 2>/dev/null || true
done

# Additional: Remove PHP packages yang mungkin terlewat
print_status "Menghapus PHP packages tambahan..."
php_related_packages=$(dpkg -l | grep -E "^ii.*php" | awk '{print $2}')
for php_pkg in $php_related_packages; do
    if [[ " ${SERVICE_PACKAGES[@]} " =~ " ${php_pkg} " ]]; then
        continue  # Sudah dihapus di loop utama
    else
        print_status "Menghapus PHP package: $php_pkg"
        apt remove --purge -y "$php_pkg" 2>/dev/null || true
    fi
done

print_success "Service packages removed"

# Step 4: Remove Service Data and Configs
print_status "Step 4: Membersihkan data dan config services..."

# Web Servers
if [ -d "/etc/apache2" ]; then
    rm -rf /etc/apache2
    print_status "Apache config dihapus"
fi

if [ -d "/etc/nginx" ]; then
    rm -rf /etc/nginx
    print_status "Nginx config dihapus"
fi

if [ -d "/var/www" ]; then
    # Hanya hapus content, bukan directory structure
    rm -rf /var/www/html/*
    rm -rf /var/www/*/
    print_status "Web content dibersihkan"
fi

# Database Servers
if [ -d "/var/lib/mysql" ]; then
    rm -rf /var/lib/mysql/*
    print_status "MySQL data dibersihkan"
fi

if [ -d "/etc/mysql" ]; then
    rm -rf /etc/mysql
    print_status "MySQL config dihapus"
fi

# PHP Configs
if [ -d "/etc/php" ]; then
    rm -rf /etc/php
    print_status "PHP config dihapus"
fi

# DNS Server
if [ -d "/etc/bind" ]; then
    rm -rf /etc/bind
    print_status "BIND config dihapus"
fi

if [ -d "/var/cache/bind" ]; then
    rm -rf /var/cache/bind/*
    print_status "BIND cache dibersihkan"
fi

# Mail Servers
if [ -d "/etc/postfix" ]; then
    rm -rf /etc/postfix
    print_status "Postfix config dihapus"
fi

if [ -d "/etc/dovecot" ]; then
    rm -rf /etc/dovecot
    print_status "Dovecot config dihapus"
fi

# FTP Servers
if [ -d "/etc/vsftpd" ]; then
    rm -rf /etc/vsftpd
    print_status "VSFTPD config dihapus"
fi

if [ -d "/etc/proftpd" ]; then
    rm -rf /etc/proftpd
    print_status "ProFTPD config dihapus"
fi

# Other Databases
if [ -d "/var/lib/postgresql" ]; then
    rm -rf /var/lib/postgresql/*
    print_status "PostgreSQL data dibersihkan"
fi

if [ -d "/etc/postgresql" ]; then
    rm -rf /etc/postgresql
    print_status "PostgreSQL config dihapus"
fi

# Redis
if [ -d "/var/lib/redis" ]; then
    rm -rf /var/lib/redis/*
    print_status "Redis data dibersihkan"
fi

if [ -d "/etc/redis" ]; then
    rm -rf /etc/redis
    print_status "Redis config dihapus"
fi

print_success "Service data and configs cleaned"

# Step 5: Clean Service Logs
print_status "Step 5: Membersihkan service logs..."

service_logs=(
    "/var/log/apache2"
    "/var/log/nginx" 
    "/var/log/mysql"
    "/var/log/mariadb"
    "/var/log/bind9"
    "/var/log/postfix"
    "/var/log/dovecot"
    "/var/log/vsftpd"
    "/var/log/php"
    "/var/log/postgresql"
    "/var/log/redis"
)

for log_dir in "${service_logs[@]}"; do
    if [ -d "$log_dir" ]; then
        rm -rf "$log_dir"/*
        print_status "Logs cleaned: $(basename "$log_dir")"
    fi
done

print_success "Service logs cleaned"

# Step 6: Clean Package Cache
print_status "Step 6: Membersihkan package cache..."

apt autoremove -y
apt autoclean
apt clean

print_success "Package cache cleaned"

# Step 7: Clean Temporary Files
print_status "Step 7: Membersihkan temporary files..."

# Clean temp directories
rm -rf /tmp/*
rm -rf /var/tmp/*

# Clean package cache
rm -rf /var/cache/apt/archives/*
rm -rf /var/cache/apt/archives/partial/*

# Clean PHP sessions and cache
if [ -d "/var/lib/php/sessions" ]; then
    rm -rf /var/lib/php/sessions/*
    print_status "PHP sessions dibersihkan"
fi

# Clean old logs (keep current)
find /var/log -name "*.log" -type f -exec truncate -s 0 {} \; 2>/dev/null || true
find /var/log -name "*.gz" -type f -delete 2>/dev/null || true
find /var/log -name "*.1" -type f -delete 2>/dev/null || true

print_success "Temporary files cleaned"

# Step 8: Final Check
print_status "Step 8: Final system check..."

# Cek apakah PHP masih ada
if dpkg -l | grep -q "^ii.*php"; then
    remaining_php=$(dpkg -l | grep "^ii.*php" | awk '{print $2}' | tr '\n' ' ')
    print_warning "Masih ada PHP packages: $remaining_php"
else
    print_success "Semua PHP packages berhasil dihapus"
fi

# Cek essential packages masih ada
essential_ok=true
for essential in "${ESSENTIAL_PACKAGES[@]}"; do
    if is_installed "$essential"; then
        continue
    else
        print_warning "Essential package missing: $essential"
        essential_ok=false
    fi
done

if $essential_ok; then
    print_success "Semua essential packages terinstall dengan baik"
else
    print_warning "Beberapa essential packages mungkin hilang"
fi

# Final Summary
echo ""
echo "=========================================="
print_success "SMART DEBIAN CLEANUP COMPLETED!"
echo "=========================================="
echo ""
echo "📋 YANG SUDAH DIBERSIHKAN:"
echo "--------------------------"
echo "✅ Service packages: ${#installed_services[@]} packages"
echo "✅ PHP packages: $(echo "$php_packages" | wc -w) packages"
echo "✅ Service config files"
echo "✅ Service data directories" 
echo "✅ Service log files"
echo "✅ Package cache"
echo "✅ Temporary files"
echo ""
echo "🔒 YANG DIPERTAHANKAN:"
echo "---------------------"
echo "✅ ${#ESSENTIAL_PACKAGES[@]} essential packages"
echo "✅ System base configuration"
echo "✅ User accounts dan home directories"
echo "✅ Network settings"
echo "✅ System logs (current)"
echo ""
echo "🚀 SISTEM BERSIH DAN SIAP UNTUK INSTALL BARU!"
echo "=========================================="

# Recommendations
echo ""
print_status "REKOMENDASI SELANJUTNYA:"
echo "• Install services yang diperlukan:"
echo "  apt install apache2 mariadb-server php phpmyadmin"
echo "• Untuk development PHP:"
echo "  apt install php php-cli php-mysql php-curl php-gd php-mbstring php-xml php-zip"
echo "• Cek system health:"
echo "  systemctl status"
echo "  df -h"
echo "  free -h"
echo ""
print_success "Cleanup selesai! System dalam keadaan bersih dan stabil!"

Simpan script tersebut. beri hak akses eksekusi

chmod +x cleanup.sh

Jika script tidak jalan, jalankan perintah berikut

sed -i 's/\r$//' cleanup.sh

jalankan script

./cleanup.sh