#!/bin/bash
#
# Donloaded from PingTool.org
#
# This script will generate Gaia configuration commands from existing system.
# It currently supports Interfaces (inc VLANS) and static routes
#
# Configuration:
#

# Bonding mode - supported options: round-robin, active-backup, xor, 8023AD
BOND_MODE='8023AD'
BOND_HASH='layer3+4'

# NTP Protocol Version
NTP_VERSION='3'

# Time zone
TIMEZONE='Etc / GMT'




#############




# CIDR convert function

function oct2cidr () {
    local mask bit cidr i
    mask=$MASK

    for i in 1 2 3 4; do
        bit=${bit}$(printf "%08d" \
            $(echo 'ibase=10;obase=2;'$(cut -d '.' -f $i <<<$mask) |bc))
    done
    cidr=$(echo -n ${bit%%0*} |wc -m)

    echo $cidr
}


# Configure bonding if present
if [ -d /proc/net/bonding/ ]; then
  for BOND in $(ls /proc/net/bonding/); do

    echo "add bonding group ${BOND: -1}"
    echo "set bonding group ${BOND: -1} mode $BOND_MODE"
    echo "set bonding group ${BOND: -1} xmit-hash-policy $BOND_HASH"
  
    for SLAVE in $(grep Slave /proc/net/bonding/$BOND | cut -d' ' -f3); do
      echo "add bonding group ${BOND: -1} interface $SLAVE"
    done
  done
fi

# Bring Interfaces Up
ifconfig | grep Ethernet | sed 's/[\.\:]/ /g' | cut -d' ' -f1 | sort -u | awk '{print "set interface", $1, "state on" }'



# Set Speed/Duplex
ifconfig | grep Ethernet | sed 's/[\.\:]/ /g' | cut -d' ' -f1 | sort -u | awk '{print "set interface", $1, "link-speed 1000M/full" }'



# Add VLAN tags
ifconfig | grep Ethernet | sed 's/\./ /g' | awk '{if ($3~/^Link/ ) print "add interface", $1, "vlan", $2}'



# Set IPs
ifconfig | awk '$2~/^Link/{_1=$1;getline;if($2~/^addr/){print _1" "$2" "$4}}' | sed -e 's/^/set interface /' -e 's/addr:/ipv4-address /' -e 's/Mask:/subnet-mask /'



# Add Routes

route -n | grep UG | grep -v Kernel | grep -v Destination | while read N;  do
    IP=$(echo $N | cut -d' ' -f1)
    GW=$(echo $N | cut -d' ' -f2)
    MASK=$(echo $N | cut -d' ' -f3)
    MASK=$(oct2cidr)

    if [[ $IP == 0.0.0.0 ]]; then
      echo "set static-route default nexthop gateway address $GW on"
    else
      echo "set static-route ${IP}/${MASK} nexthop gateway address $GW on"
    fi
done


# Set up NTP

if [ -f /etc/sysconfig/ntp ]; then
  NTP1=$(cat /etc/sysconfig/ntp | grep SERVER1 | cut -d'=' -f2)
  NTP2=$(cat /etc/sysconfig/ntp | grep SERVER2 | cut -d'=' -f2)

  if [[ $NTP1 ]]; then
    echo "set ntp active on"
    echo "set ntp server primary $NTP1 version $NTP_VERSION"
  fi

  if [[ $NTP2 ]]; then
    echo "set ntp server secondary $NTP2 version $NTP_VERSION"
  fi

fi



# Set timezone

echo "set timezone $TIMEZONE"


# Set DNS
if [ -f /etc/sysconfig/ntp ]; then

  N=0
  for DNS in $(cat /etc/resolv.conf | grep nameserver | cut -d' ' -f2); do
    case $N in
      0)
          echo "set dns primary ipv4-address $DNS" ;;
      1)
          echo "set dns secondary ipv4-address $DNS" ;;
      2)
          echo "set dns tertiary ipv4-address $DNS" ;;
      *)
          exit 0
    esac
  done
fi


