#!/bin/sh
exec >>/root/post-install.out 2>&1
set -x

# Script begins
type bash
cd `dirname $0`
pwd
PATH=$PATH:.


#fdisk -l /dev/sda | grep '^/dev/sda3' | cut -d' ' -f1
#blkid | awk '{print substr($1, 0, length($1) - 1)}' | grep '^/dev/sda3'


if blkid | awk '{print substr($1, 0, length($1) - 1)}' | grep '^/dev/sda3'; then

	parted /dev/sda rm 3

fi

if blkid | awk '{print substr($1, 0, length($1) - 1)}' | grep '^/dev/vda3'; then

	parted /dev/vda rm 3

fi


echo localhost > /etc/hostname


mkdir -p /root/.local/bin
chmod -R 0700 /root/.local
ln -s /root/.local/bin /root/bin


sed -i "s/# export LS_OPTIONS='--color=auto'/export LS_OPTIONS='--color=auto'/g" /root/.bashrc
sed -i "s/# eval \"\`dircolors\`\"/eval \"\`dircolors\`\"/g" /root/.bashrc
sed -i "s/# alias ls='ls \$LS_OPTIONS'/alias ls='ls \$LS_OPTIONS'/g" /root/.bashrc
sed -i "s/# alias ll='ls \$LS_OPTIONS -l'/alias ll='ls \$LS_OPTIONS -l'/g" /root/.bashrc
sed -i "s/# alias l='ls \$LS_OPTIONS -lA'/alias l='ls \$LS_OPTIONS -lA'/g" /root/.bashrc

cat <<EOT >> /root/.bashrc

HISTCONTROL=ignoreboth
HISTFILESIZE=999999999
HISTSIZE=999999999


txtblk='\033[0;30m' # Black - Regular
txtred='\033[0;31m' # Red
txtgrn='\033[0;32m' # Green
txtylw='\033[0;33m' # Yellow
txtblu='\033[0;34m' # Blue
txtpur='\033[0;35m' # Purple
txtcyn='\033[0;36m' # Cyan
txtwht='\033[0;37m' # White
bldblk='\033[1;30m' # Black - Bold
bldred='\033[1;31m' # Red
bldgrn='\033[1;32m' # Green
bldylw='\033[1;33m' # Yellow
bldblu='\033[1;34m' # Blue
bldpur='\033[1;35m' # Purple
bldcyn='\033[1;36m' # Cyan
bldwht='\033[1;37m' # White
undblk='\033[4;30m' # Black - Underline
undred='\033[4;31m' # Red
undgrn='\033[4;32m' # Green
undylw='\033[4;33m' # Yellow
undblu='\033[4;34m' # Blue
undpur='\033[4;35m' # Purple
undcyn='\033[4;36m' # Cyan
undwht='\033[4;37m' # White
bakblk='\033[40m'   # Black - Background
bakred='\033[41m'   # Red
bakgrn='\033[42m'   # Green
bakylw='\033[43m'   # Yellow
bakblu='\033[44m'   # Blue
bakpur='\033[45m'   # Purple
bakcyn='\033[46m'   # Cyan
bakwht='\033[47m'   # White
txtrst='\033[0m'    # Text Reset

PS1='\n[\['\$bldgrn'\]\u\['\$txtrst'\] \['\$bldred'\]@\['\$txtrst'\] \['\$bldylw'\]\h\['\$txtrst'\] : \['\$bldblu'\]\w\['\$txtrst'\]]\n   \\$> '


export LANGUAGE=en_US.UTF-8:en
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

unset MAILCHECK

EOT


# Edit the root user .profile

touch /root/.profile

cat <<EOT > /root/.profile
# ~/.profile: executed by Bourne-compatible login shells.

if [ -n "\$BASH" ]; then
    if [ -f ~/.bashrc ]; then
        . ~/.bashrc
    fi
fi

# set PATH so it includes user's private bin if it exists
if [ -h ~/bin ]; then
    PATH=~/bin:\$PATH
fi


mesg n || true

EOT


chown -hR root: /root


# Create the MOTD

# install lsb-release
# install figlet to enable ASCII art
# install python-apt to show available update(s) with motd
apt -y install lsb-release figlet python-apt

if [ -d "/etc/update-motd.d" ] ; then
    rm /etc/update-motd.d/*
else
    # create directory
    mkdir /etc/update-motd.d/
fi

# change to new directory
#cd /etc/update-motd.d/

# create dynamic files
touch /etc/update-motd.d/{00-header,10-sysinfo,20-updates,90-footer}

# make files executable
chmod +x /etc/update-motd.d/*

# remove MOTD file
if [ -f "/etc/motd" ] ; then
    rm /etc/motd
fi


cat <<EOT > /etc/update-motd.d/00-header
#!/bin/sh
#

[ -r /etc/lsb-release ] && . /etc/lsb-release
 
if [ -z "\$DISTRIB_DESCRIPTION" ] && [ -x /usr/bin/lsb_release ]; then
        # Fall back to using the very slow lsb_release utility
        DISTRIB_DESCRIPTION=\$(lsb_release -s -d)
fi

printf "\n" 
figlet \$(hostname)
printf "%s\n" "\$(hostname -f)"
printf "\n\n"

printf "Welcome to %s (%s)\n" "\$DISTRIB_DESCRIPTION" "\$(uname -r)"
printf "\n"

EOT

cat <<EOT > /etc/update-motd.d/10-sysinfo
#!/bin/sh
#

date=\`date\`
load=\`cat /proc/loadavg | awk '{print \$1}'\`
root_usage=\`df -h / | awk '/\// {print \$(NF-1)}'\`
memory_usage=\`free -m | awk '/Mem/ { printf("%3.1f%%", \$3/\$2*100) }'\`
swap_usage=\`free -m | awk '/Swap/ { printf("%3.1f%%", \$3/\$2*100) }'\`
users=\`users | wc -w\`
uptime=\`uptime | grep -ohe 'up .*' | sed 's/,/\ hours/g' | awk '{ printf \$2" "\$3 }'\`
processes=\`ps aux | wc -l\`
#ip=\`ifconfig \$(route | grep default | awk '{ print \$8 }') | grep "inet addr" | awk -F: '{print \$2}' | awk '{print \$1}'\`
ip4=\`ip a | grep glo | grep inet | awk '{print \$2}' | head -1 | cut -f1 -d/\`
ip6=\`ip a | grep glo | grep inet6 | awk '{print \$2}' | head -1 | cut -f1 -d/\`

echo "System information as of: \$date"
echo
printf "System Uptime:\t%s\n\n" "\$uptime"

printf "IPv4 Address:\t%s\n" \$ip4
printf "IPv6 Address:\t%s\n\n" \$ip6

printf "System load:\t%s\tMemory usage:\t%s\n" \$load \$memory_usage
printf "Usage On /:\t%s\tSwap Usage:\t%s\n" \$root_usage \$swap_usage
printf "Local Users:\t%s\tProcesses:\t%s\n" \$users \$processes

printf "\n\n"

EOT

cat <<EOT > /etc/update-motd.d/20-updates
#!/usr/bin/python
#

import sys
import subprocess
import apt_pkg

DISTRO = subprocess.Popen(["lsb_release", "-c", "-s"],
                          stdout=subprocess.PIPE).communicate()[0].strip()

class OpNullProgress(object):
    '''apt progress handler which supresses any output.'''
    def update(self):
        pass
    def done(self):
        pass

def is_security_upgrade(pkg):
    '''
    Checks to see if a package comes from a DISTRO-security source.
    '''
    security_package_sources = [("Ubuntu", "%s-security" % DISTRO),
                               ("Debian", "%s-security" % DISTRO)]

    for (file, index) in pkg.file_list:
        for origin, archive in security_package_sources:
            if (file.archive == archive and file.origin == origin):
                return True
    return False

# init apt and config
apt_pkg.init()

# open the apt cache
try:
    cache = apt_pkg.Cache(OpNullProgress())
except SystemError, e:
    sys.stderr.write("Error: Opening the cache (%s)" % e)
    sys.exit(-1)

# setup a DepCache instance to interact with the repo
depcache = apt_pkg.DepCache(cache)

# take into account apt policies
depcache.read_pinfile()

# initialise it
depcache.init()

# give up if packages are broken
if depcache.broken_count > 0:
    sys.stderr.write("Error: Broken packages exist.")
    sys.exit(-1)

# mark possible packages
try:
    # run distro-upgrade
    depcache.upgrade(True)
    # reset if packages get marked as deleted -> we don't want to break anything
    if depcache.del_count > 0:
        depcache.init()

    # then a standard upgrade
    depcache.upgrade()
except SystemError, e:
    sys.stderr.write("Error: Couldn't mark the upgrade (%s)" % e)
    sys.exit(-1)

# run around the packages
upgrades = 0
security_upgrades = 0
for pkg in cache.packages:
    candidate = depcache.get_candidate_ver(pkg)
    current = pkg.current_ver

    # skip packages not marked as upgraded/installed
    if not (depcache.marked_install(pkg) or depcache.marked_upgrade(pkg)):
        continue

    # increment the upgrade counter
    upgrades += 1

    # keep another count for security upgrades
    if is_security_upgrade(candidate):
        security_upgrades += 1

    # double check for security upgrades masked by another package
    for version in pkg.version_list:
        if (current and apt_pkg.version_compare(version.ver_str, current.ver_str) <= 0):
            continue
        if is_security_upgrade(version):
            security_upgrades += 1
            break

print "%d updates to install." % upgrades
print "%d are security updates." % security_upgrades
print "" # leave a trailing blank line

EOT

cat <<EOT > /etc/update-motd.d/90-footer
#!/bin/sh
#

[ -f /etc/motd.tail ] && cat /etc/motd.tail || true

printf "\n"

EOT


apt update ; apt -y --with-new-pkgs upgrade
sleep 1
apt autoremove ; apt clean ; apt autoclean ; updatedb


sed -i -e 's/GRUB_CMDLINE_LINUX_DEFAULT="\(.*\)"/GRUB_CMDLINE_LINUX_DEFAULT="\1 net.ifnames=0 biosdevname=0"/g' /etc/default/grub
update-grub
sed -i -e 's/\(enp\|ens\)[0-9a-z0-9]\+/eth0/g' /etc/network/interfaces


exit 0

