#!/bin/bash

# set -x

export HOME=~root
export PATH=/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin

if [ -f /etc/redhat-release ]
then
    # CentOS release 6.7 (Final)
    OS=$(awk ' { print "%s-%s", $1, $3 }' < /etc/redhat-release)
elif [ -f /etc/lsb-release ]
then
    eval "$(cat /etc/lsb-release)"
    OS="$DISTRIB_ID-$DISTRIB_RELEASE"
elif [ -f /etc/debian_version ]
then
    OS="Debian-$(cat /etc/debian_version)"
fi

case "$OS" in
    LinuxMint-17|LinuxMint-17.*|LinuxMint-18|LinuxMint-18.*|LinuxMint-19|LinuxMint-19.*|Ubuntu-18.*|Ubuntu-20.*|Ubuntu-22.*|Debian-[89].*|Debian-1[012].*)
        # This probably works on Linux Mint 17.1-17.3.
        # I'm also trying it on Debian-8.2.
        # Obtained from: http://askubuntu.com/questions/146921/how-do-i-apt-get-y-dist-upgrade-without-a-grub-config-prompt
        if ! output=$(apt-get -y update 2>&1)
        then
            echo "$0: apt-get -y update failed" 1>&2
            echo "$output" 1>&2
            exit 1
        fi
        if ! output=$(DEBIAN_FRONTEND=noninteractive apt-get \
            -y \
            -o Dpkg::Options::="--force-confdef" \
            -o Dpkg::Options::="--force-confold" \
            dist-upgrade 2>&1)
        then
            echo "$0: apt-get dist-upgrade failed" 1>&2
            echo "$output" 1>&2
            exit 1
        fi
        if ! output=$(apt-get autoclean 2>&1)
        then
            echo "$0: apt-get autoclean failed" 1>&2
            echo "$output" 1>&2
            exit 1
        fi
        if ! output=$(apt-get autoremove --yes --purge 2>&1)
        then
            echo "$0: apt-get autoremove --yes --purge failed" 1>&2
            echo "$output" 1>&2
            exit 1
        fi
        ;;
    Debian-7.*)
        # This used to work well, but sadly, not anymore
        export PATH="$PATH":'/usr/local/sbin:/usr/sbin:/sbin'

        if ! output=$(apt-get -y -f update 2>&1)
        then
            echo "$0: apt-get -y -f update failed" 1>&2
            echo "$output" 1>&2
            exit 1
        fi
        if ! output=$(apt-get -y -f upgrade 2>&1)
        then
            echo "$0: apt-get -y -f upgrade failed" 1>&2
            echo "$output" 1>&2
            exit 1
        fi
        if ! output=$(apt-get autoclean 2>&1)
        then
            echo "$0: apt-get autoclean failed" 1>&2
            echo "$output" 1>&2
            exit 1
        fi
        ;;
    CentOS-6.*)
        if ! output=$(yum -y update 2>&1)
        then
            echo "$0: yum -y update failed" 1>&2
            echo "$output" 1>&2
            exit 1
        fi
        ;;
    *)
        echo "$0: $OS unrecognized" 1>&2
        exit 1
        ;;
esac

echo "Terminated normally"