#!/bin/bash
# Info: Script to install Resolv packages
# Author: JesusPerezLorenzo  
# Release: 1.0 
# Date: 30-10-2023
USAGE="install-resolv.sh "

[ "$1" == "-h"  ] && echo "$USAGE"  && exit 1

_config_resolver() {
  [ -z "$NAMESERVERS" ]  && return 
  local resolv_cfg_path
  local resolv_cfg_file
  # if [ ! -r "/etc/resolvconf/resolv.conf.d" ] ; then 
  #   sudo apt install resolvconf -y
  #   sudo timeout -k 10 20 systemctl enable --now resolvconf
  #   sudo timeout -k 10 20 systemctl restart resolvconf
  #   sudo systemctl enable resolvconf.service
  # fi
  if [ -d "/etc/resolvconf/resolv.conf.d" ] ; then 
    resolv_cfg_path=/etc/resolvconf/resolv.conf.d
    resolv_cfg_file="head"
  else 
    resolv_cfg_path=/etc
    resolv_cfg_file="resolv.conf"
     chattr -i "$resolv_cfg_path/$resolv_cfg_file" 
  fi
  [ ! -r "$resolv_cfg_path/_$resolv_cfg_file" ] && sudo mv "$resolv_cfg_path/$resolv_cfg_file" "$resolv_cfg_path/_$resolv_cfg_file"
  grep -v "^nameserver" "$resolv_cfg_path/_$resolv_cfg_file" | sudo tee "$resolv_cfg_path/$resolv_cfg_file" &>/dev/null
  echo "
#options rotate
options timeout:1
" | sudo tee -a "$resolv_cfg_path/$resolv_cfg_file" &>/dev/null
  for ns in $NAMESERVERS 
  do
    echo "nameserver $ns" | sudo tee -a "$resolv_cfg_path/$resolv_cfg_file" &>/dev/null
  done
  #grep "^nameserver" "$resolv_cfg_path/_$resolv_cfg_file" | sudo tee -a "$resolv_cfg_path/$resolv_cfg_file" &>/dev/null
  [ -n "$DOMAINS_SEARCH" ] && echo "search $DOMAINS_SEARCH" | sudo tee -a "$resolv_cfg_path/$resolv_cfg_file" &>/dev/null
  if [ -d "/etc/resolvconf/resolv.conf.d" ] ; then 
     sudo timeout -k 10 20 systemctl restart resolvconf
  else
     chattr +i "$resolv_cfg_path/$resolv_cfg_file" 
  fi
}

[ -r "./env-resolv"  ] && . ./env-resolv
# Update and add packages to installation
[ -z "$1" ] || [ "$1" == "resolver" ] && _config_resolver
exit 0
