#!/bin/bash
###Script by Ngo Anh Tuan-lowendviet.com.

#Update 2018-Dec-30
#Change log:
#2018-Dec-30: Initialize script
#2019-Jan-12: Add support for debian 9
#2021-Apr-1: Add support for Ubuntu 20.04
#2021-Jun-8: Auto extend disk and add default route for Ubuntu 18.04
#2021-Jun-17: Fix bug snapshot-restore doesn't get IP. Add auto update for the script
#2023-Mar-06: Add support for Ubuntu 22.04
export PATH=$PATH:/usr/bin:/bin:/usr/sbin:/sbin

function getConfigSubnet {
  configmask=$1
  configsubnet="/24"
  if [ "$configmask" = "255.255.0.0" ]; then
      configsubnet="/16"
  elif [ "$configmask" = "255.255.128.0" ]; then
      configsubnet="/17"
  elif [ "$configmask" = "255.255.192.0" ]; then
      configsubnet="/18"
  elif [ "$configmask" = "255.255.224.0" ]; then
      configsubnet="/19"
  elif [ "$configmask" = "255.255.240.0" ]; then
      configsubnet="/20"
  elif [ "$configmask" = "255.255.248.0" ]; then
      configsubnet="/21"
  elif [ "$configmask" = "255.255.252.0" ]; then
      configsubnet="/22"
  elif [ "$configmask" = "255.255.254.0" ]; then
      configsubnet="/23"
  elif [ "$configmask" = "255.255.255.128" ]; then
      configsubnet="/25"
  elif [ "$configmask" = "255.255.255.192" ]; then
      configsubnet="/26"
  elif [ "$configmask" = "255.255.255.224" ]; then
      configsubnet="/27"
  elif [ "$configmask" = "255.255.255.240" ]; then
      configsubnet="/28"
  elif [ "$configmask" = "255.255.255.248" ]; then
      configsubnet="/29"
  elif [ "$configmask" = "255.255.255.252" ]; then
      configsubnet="/30"
  fi
  echo $configsubnet
}

#Identify the distro
if [ -f /etc/os-release ]; then
    # freedesktop.org and systemd
    . /etc/os-release
    OS=$NAME
    VER=$VERSION_ID
elif type lsb_release >/dev/null 2>&1; then
    # linuxbase.org
    OS=$(lsb_release -si)
    VER=$(lsb_release -sr)
elif [ -f /etc/lsb-release ]; then
    # For some versions of Debian/Ubuntu without lsb_release command
    . /etc/lsb-release
    OS=$DISTRIB_ID
    VER=$DISTRIB_RELEASE
elif [ -f /etc/debian_version ]; then
    # Older Debian/Ubuntu/etc.
    OS=Debian
    VER=$(cat /etc/debian_version)
elif [ -f /etc/SuSe-release ]; then
    # Older SuSE/etc.
    ...
elif [ -f /etc/redhat-release ]; then
    # Older Red Hat, CentOS, etc.
    ...
else
    # Fall back to uname, e.g. "Linux <version>", also works for BSD, etc.
    OS=$(uname -s)
    VER=$(uname -r)
fi

forcePwChange="/etc/lev/forcePwChange"

if [ "$OS" = "CentOS Linux" ]; then
    #CentOS
    mount /dev/sr1 /mnt/srip
    configip=$(sed '1q;d' /mnt/srip/config.txt | tr -d '\r\n')
    configmask=$(sed '3q;d' /mnt/srip/config.txt | tr -d '\r\n')
    configgw=$(sed '5q;d' /mnt/srip/config.txt| tr -d '\r\n')
    currentip=$(ip -f inet a show eth0| grep inet| awk '{ print $2}' | cut -d/ -f1)
    if [ "$configip" != "$currentip" ]; then
        /usr/sbin/ifdown eth0
        sed -i "/IPADDR=/c\IPADDR=${configip}" /etc/sysconfig/network-scripts/ifcfg-eth0
        sed -i "/NETMASK=/c\NETMASK=${configmask}" /etc/sysconfig/network-scripts/ifcfg-eth0
        sed -i "/GATEWAY=/c\GATEWAY=${configgw}" /etc/sysconfig/network-scripts/ifcfg-eth0
        /usr/sbin/ifup eth0
        sleep 10
        /usr/sbin/ifdown eth0 && /usr/sbin/ifup eth0
    fi

    # Expand disk
    growpart /dev/vda 2
    resize2fs /dev/vda2
elif [ "$OS" = "Ubuntu" -a "$VER" = "18.04" ]; then
    #Ubuntu 18
    # crontab -e @reboot sudo /etc/lev/setipLinux.sh #### REMEMBER SUDO COMMAND ####
    mount /dev/sr1 /mnt/srip
    configip=$(sed '1q;d' /mnt/srip/config.txt | tr -d '\r\n')
    configmask=$(sed '3q;d' /mnt/srip/config.txt | tr -d '\r\n')
    configgw=$(sed '5q;d' /mnt/srip/config.txt | tr -d '\r\n')
    network_card=$(ip -o link show | awk '{print $2,$9}' | grep ens | cut -d: -f1)
    currentip=$(ip -f inet a show ${network_card}| grep inet| awk '{ print $2}' | cut -d/ -f1)
    if [ "$configip" != "$currentip" ]; then
        configsubnet=$(getConfigSubnet $configmask)
        sed -i -e "s/ens.*/$network_card:/g" /etc/netplan/50-cloud-init.yaml
        sed -i -e "s|- [0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\/[0-9]*|- $configip$configsubnet|g" /etc/netplan/50-cloud-init.yaml
        sed -i -e "s/gateway4.*/gateway4: $configgw/g" /etc/netplan/50-cloud-init.yaml
        sleep 10
        netplan apply
    fi

    # Expand disk
    growpart /dev/vda 3
    resize2fs /dev/vda3

    # Add default route
    ip route add default via ${configgw} dev ${network_card} onlink
elif [ "$OS" = "Ubuntu" -a "$VER" = "20.04" ] || [ "$OS" = "Ubuntu" -a "$VER" = "22.04" ]; then
    #Ubuntu 22
    # crontab -e @reboot sudo /etc/lev/cloud-init.sh #### REMEMBER SUDO COMMAND ####
    mount /dev/sr1 /mnt/srip
    configip=$(sed '1q;d' /mnt/srip/config.txt | tr -d '\r\n')
    configmask=$(sed '3q;d' /mnt/srip/config.txt | tr -d '\r\n')
    configgw=$(sed '5q;d' /mnt/srip/config.txt | tr -d '\r\n')
    network_card=$(ip -o link show | awk '{print $2,$9}' | grep ens | cut -d: -f1)
    currentip=$(ip -f inet a show ${network_card}| grep inet| awk '{ print $2}' | cut -d/ -f1 | grep -v 127.*)
    if [ "$configip" != "$currentip" ]; then
        configsubnet=$(getConfigSubnet $configmask)
        sed -i -e "s/ens.*/$network_card:/g" /etc/netplan/00-installer-config.yaml
        sed -i -e "s|- [0-9]*\.[0-9]*\.[0-9]*\.[0-9]*\/[0-9]*|- $configip$configsubnet|g" /etc/netplan/00-installer-config.yaml
        defaultGatewayDeclarationLine=$(awk '/to: default/{ print NR; exit }' /etc/netplan/00-installer-config.yaml)
        currentGatewayLine=$(($defaultGatewayDeclarationLine + 1))
        currentGateway=$(sed "${currentGatewayLine}q;d" /etc/netplan/00-installer-config.yaml | cut -d ":" -f2 | awk '{$1=$1;print}')
        sed -i -e "s/${currentGateway}/${configgw}/g" /etc/netplan/00-installer-config.yaml
        if grep -q "on-link: false" /etc/netplan/00-installer-config.yaml; then
          sed -i "s/on-link: false/on-link: true/" /etc/netplan/00-installer-config.yaml
        else
          onlinkLine=$((currentGatewayLine + 1))
          onlinkState=$(sed "${onlinkLine}q;d" /etc/netplan/00-installer-config.yaml  | cut -d ":" -f2 | awk '{$1=$1;print}')
          if [ "$onlinkState" != "true" ]; then
            sed -i "${onlinkLine} i \ \ \ \ \ \ \ \ on-link: true" /etc/netplan/00-installer-config.yaml
          fi
        fi
        sleep 3
        netplan apply
    fi
    # Expand disk
    rootPartition=$(df -hT | grep /$ | cut -d ' ' -f1)
    partitionNo=$(echo "$rootPartition" | awk -F'[^0-9]+' '{ print $2 }')
    diskName=$(echo "$rootPartition" | cut -d"$partitionNo" -f1)
    growpart "$diskName" "$partitionNo"
    resize2fs "$rootPartition"

    # Forced changing password at the first time of login
    if [ ! -f ${forcePwChange} ] || [ "$(cat ${forcePwChange})" != 1 ]; then
      chage -d '1970-01-01' root
      echo "1" > ${forcePwChange}
    fi
elif [ "$OS" = "Debian GNU/Linux" ]; then
    mount /dev/sr1 /mnt/srip
    configip=$(sed '1q;d' /mnt/srip/config.txt | tr -d '\r\n')
    configmask=$(sed '3q;d' /mnt/srip/config.txt | tr -d '\r\n')
    configgw=$(sed '5q;d' /mnt/srip/config.txt | tr -d '\r\n')
    network_card=$(ip -o link show | awk '{print $2,$9}' | grep ens | cut -d: -f1)
    currentip=$(ip -f inet a show ${network_card}| grep inet| awk '{ print $2}' | cut -d/ -f1)
    if [ "$configip" != "$currentip" ]; then
        ifdown ${network_card}
        sed -i -e "s/ens.[0-9]/$network_card/g" /etc/network/interfaces
        sed -i "/address/c\address ${configip}" /etc/network/interfaces
        sed -i "/netmask/c\netmask ${configmask}" /etc/network/interfaces
        sed -i "/gateway/c\gateway ${configgw}" /etc/network/interfaces
        ifup ${network_card}
    fi
    # Expand disk (Debian 11)
    growpart /dev/vda 1 || true
    resize2fs /dev/vda1 || true
    growpart /dev/sda 1 || true
    resize2fs /dev/sda1 || true
fi

if [[ "$1" == "update" ]]; then
  #Update script
  sleep 100
  wget http://file.lowendviet.com/Scripts/cloud-init.sh -N -P /etc/lev/ && chmod 777 /etc/lev/cloud-init.sh | true
fi
