#!/bin/bash

set -e  # Exit immediately if any command fails

# Update and install prerequisites
apt-get update -y
apt-get install -y build-essential
add-apt-repository -y ppa:maxmind/ppa
apt-get update
apt-get install -y libmaxminddb0 libmaxminddb-dev mmdb-bin geoipupdate
apt-get install -y libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev

# Configure GeoIP
cat << EOF > /etc/GeoIP.conf
AccountID <YOUR ACCOUNTID>
LicenseKey <YOUR LICENSE KEY>
EditionIDs GeoLite2-ASN GeoLite2-City GeoLite2-Country
EOF

geoipupdate

# Download and build NGINX with GeoIP2 module
NGINX_VERSION=1.21.4
NGINX_MODULE_PATH=/usr/local/src/ngx_http_geoip2_module

cd /usr/local/src
wget https://nginx.org/download/nginx-$NGINX_VERSION.tar.gz
tar xzvf nginx-$NGINX_VERSION.tar.gz
git clone https://github.com/leev/ngx_http_geoip2_module $NGINX_MODULE_PATH
cd nginx-$NGINX_VERSION

./configure \
    --add-dynamic-module=$NGINX_MODULE_PATH \
    $(nginx -V) --with-compat \
    --with-http_ssl_module

make
make install

# Configure NGINX service
cat << EOF > /lib/systemd/system/nginx.service
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF


# Configure NGINX with GeoIP2 module
cat << EOF > /usr/local/nginx/conf/nginx.conf
worker_processes  1;
load_module modules/ngx_http_geoip2_module.so;
pid        /run/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    geoip2 /usr/share/GeoIP/GeoLite2-Country.mmdb {
        \$geoip2_data_country_code country iso_code;
    }

    map \$geoip2_data_country_code \$backend {
        default <DEFAULT DESTINATION IP ADDRESS>;
        US <DESTINATION IP ADDRESS FOR US>;
        NP <DESTINATION IP ADDRESS FOR NEPAL>;
    }

    log_format clog  "\$geoip2_data_country_code triggered \$backend";
    access_log logs/access.log clog;
    server {
        listen 80;
        server_name <YOUR DOMAIN>;
        location / {
            proxy_pass \$backend;
        }
    }
}
EOF

# Start NGINX 
systemctl unmask nginx.service
systemctl start nginx
# Weekly update geoip database
echo "0 0 * * 0 geoipupdate -f /etc/GeoIP.conf" | crontab -
