#!/bin/bash
#
# Copyright (c) 2006-2021 Wade Alcorn - wade@bindshell.net
# Browser Exploitation Framework (BeEF) - http://beefproject.com
# See the file 'doc/COPYING' for copying permission
#

# Install the MaxMind GeoIP database

set -euo pipefail
IFS=$'\n\t'

GEOIP_PATH="/opt/GeoIP"

info()  { echo -e "\\033[1;36m[INFO]\\033[0m  $*"; }
warn()  { echo -e "\\033[1;33m[WARNING]\\033[0m  $*"; }
fatal() { echo -e "\\033[1;31m[FATAL]\\033[0m  $*"; exit 1 ; }

command_exists () {
  command -v "${1}" >/dev/null 2>&1
}

get_permission () {
  warn "This script will install the MaxMind GeoLite database in ${GEOIP_PATH}"

  read -rp  "Are you sure you wish to continue (Y/n)? "
  if [ "$(echo "${REPLY}" | tr "[:upper:]" "[:lower:]")" = "n" ] ; then
    fatal 'Installation aborted'
  fi
}

check_deps() {
  if ! command_exists /usr/bin/curl
  then
    fatal "/usr/bin/curl is not installed"
  fi
  if ! command_exists /bin/gunzip
  then
    fatal "/bin/gunzip is not installed"
  fi
  if ! command_exists /bin/tar
  then
    fatal "/bin/tar is not installed"
  fi
}

check_perms() {
  /bin/mkdir -p "${GEOIP_PATH}"

  if ! [ -w "${GEOIP_PATH}" ]
  then
    fatal "${GEOIP_PATH} is not writable"
  fi
}

install() {
  info 'Downloading MaxMind GeoLite2-City database ...'
  #/usr/bin/curl -O https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz
  /usr/bin/curl -O https://web.archive.org/web/20191227182209/https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz

  info 'Extracting GeoLite2-City.tar.gz ...'
  /bin/gunzip GeoLite2-City.tar.gz
  /bin/tar xvf GeoLite2-City.tar

  info "Installing to ${GEOIP_PATH} ..."
  /bin/mv GeoLite2-City_*/* "${GEOIP_PATH}"

  info 'Cleaning up ...'
  /bin/rm GeoLite2-City.tar
  /bin/rmdir GeoLite2-City_*

  info 'Done!'
}

main() {
  get_permission
  check_deps
  check_perms
  install
}

main "$@"

