#!/bin/bash

# Need to find current path
# Because current directory is user home directory
SCRIPTPATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"

# Create an upgrade script in the root directory
cat > "$1/root/upgrade.sh" << EOF

# Make this script unattended
export DEBIAN_FRONTEND=noninteractive

echo 'Fix debconf database'
FIXDB='/usr/share/debconf/fix_db.pl'; [ -f "\$FIXDB" ] && perl "\$FIXDB"

function start_stop_services () {
    echo "\$1 services"
    [ -f '/etc/apache2/apache2.conf' ] && eval service apache2 \$1
    [ -f '/etc/mysql/debian.cnf' ] && eval service mysql \$1
}

apt-get update
start_stop_services start
apt-get -y --autoremove -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold dist-upgrade
apt-get -y --autoremove -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold autopurge
apt-get -y clean
if [ -e *.deb ]; then
    dpkg -i *.deb
    rm *.deb
fi
start_stop_services stop

echo
echo "________________________________________"
echo ' Upgrade finished'
echo "‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾"
EOF

# Execute and remove the script when done
"${SCRIPTPATH}"/chroot-dir.sh "$1/root" "bash /upgrade.sh"
rm -f "$1/root/upgrade.sh" 
