os_install_epoch.sh

20th February 2018 at 11:57am
Bash CodeSnippets

I cobbled this together from a couple of online sources in a time before I knew how to write good Bash code. It's still useful though.

#!/bin/bash

PLATFORM="$(uname -s)"

case "${PLATFORM,,}" in
  linux)
    # http://free-electrons.com/blog/find-root-device/
    MAJOR_ROOTFS="$(mountpoint -d / | cut -f 1 -d ':')"
    MINOR_ROOTFS="$(mountpoint -d / | cut -f 2 -d ':')"
    DEV_ROOTFS="$(awk {'if ($1 == "'${MAJOR_ROOTFS}'" && $2 == "'${MINOR_ROOTFS}'") print $4 '} /proc/partitions)"
    if [ -r "/dev/$DEV_ROOTFS" ] ; then
      if [[ "$(dumpe2fs "/dev/$DEV_ROOTFS" 2>&1)" =~ [Ff]ilesystem\ [Cc]reated\ *:\ *([a-zA-Z0-9][a-zA-Z0-9:\ 0-]+) ]] ; then
        CREATED_ROOTFS="$(date -d "${BASH_REMATCH[1]}" +"%s")"
        if [[ "$CREATED_ROOTFS" =~ ^[0-9]+$ ]] ; then
          echo "$CREATED_ROOTFS"
          exit 0
        fi
      fi
    fi

    # http://askubuntu.com/questions/1352/how-can-i-tell-what-date-ubuntu-was-installed
    if [ -r "/etc/lsb-release" ] ; then
      source "/etc/lsb-release"
      if [ "${DISTRIB_ID,,}" == "ubuntu" ] && \
         [[ "${DISTRIB_RELEASE%%.*}" -ge 12 ]] && \
         [ -d "/var/log/installer/" ] ; then
        for file in /var/log/installer/* ; do
          MODIFIED_INSTALLER="$(stat -c "%Y" "$file")"
          if [[ "$MODIFIED_INSTALLER" =~ ^[0-9]+$ ]] ; then
            echo "$MODIFIED_INSTALLER"
            exit 0
          fi
        done
      fi
    fi

    >&2 echo "Unknown installation date."
    exit 1
    ;;

  *)
    >&2 echo "Do not understand platform type $PLATFORM."
    exit 2
    ;;
esac