#!/bin/bash

# Pastikan script dijalankan sebagai root
if [ "$(id -u)" -ne 0 ]; then
  echo "Harap jalankan script ini sebagai root atau sudo."
  exit 1
fi

echo "Memperbarui indeks paket..."
apt-get update -y

echo "Menginstal Squid Proxy Server..."
apt-get install squid -y

echo "Membuat backup konfigurasi asli Squid..."
cp /etc/squid/squid.conf /etc/squid/squid.conf.bak

echo "Menerapkan konfigurasi Squid baru untuk Web Caching..."
cat <<EOF > /etc/squid/squid.conf
# Port default proxy
http_port 3128

# ACL untuk mengizinkan jaringan lokal (sesuaikan dengan subnet Anda jika perlu)
acl localnet src 10.0.0.0/8
acl localnet src 172.16.0.0/12
acl localnet src 192.168.0.0/16

# ACL keamanan port standar
acl SSL_ports port 443
acl Safe_ports port 80          # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl CONNECT method CONNECT

# Aturan akses HTTP
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost manager
http_access deny manager
http_access allow localnet
http_access allow localhost
http_access deny all

# ==========================================
# KONFIGURASI CACHING WEB
# ==========================================

# 1. Alokasi memori RAM untuk caching objek-objek kecil agar lebih cepat (misal: 256 MB)
cache_mem 256 MB

# 2. Maksimum ukuran file yang akan disimpan di RAM
maximum_object_size_in_memory 512 KB

# 3. Direktori cache pada Disk (ufs, Lokasi, Ukuran Max: 1000MB (1GB), 16 direktori L1, 256 direktori L2)
cache_dir ufs /var/spool/squid 1000 16 256

# 4. Batasan ukuran file cache di Disk (min 0 KB, max 50 MB)
minimum_object_size 0 KB
maximum_object_size 50 MB

# 5. Tempat log akses proxy
access_log daemon:/var/log/squid/access.log squid
coredump_dir /var/spool/squid

# 6. Pola refresh untuk menentukan seberapa lama objek disimpan (Standar bawaan Squid)
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern .               0       20%     4320
EOF

echo "Mengaktifkan dan menjalankan ulang layanan Squid..."
# Di Debian 13, systemd akan otomatis menjalankan 'squid -z' saat service di-restart
systemctl restart squid
systemctl enable squid

echo "---------------------------------------------------"
echo "Instalasi dan Konfigurasi Proxy Server (Squid) Selesai!"
echo "Squid berjalan pada Port 3128."
echo "Fitur Caching Web telah diaktifkan dengan alokasi:"
echo " - 256 MB RAM Cache"
echo " - 1000 MB (1GB) Disk Cache pada /var/spool/squid"
echo "Klien dari jaringan lokal (192.168.x.x, 10.x.x.x, 172.16.x.x) dapat menggunakan proxy ini."
