#!/usr/bin/perl

use strict;
use warnings;

use File::stat ();
use Getopt::Long;

use PVE::Tools;
use PVE::Cluster;
use PVE::SafeSyslog;
use PVE::INotify;
use PVE::RPCEnvironment;
use PVE::API2::APT;

$ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';

initlog('pveupgrade');

die "please run as root\n" if $> != 0;

PVE::INotify::inotify_init();
my $nodename = PVE::INotify::nodename();

my $rpcenv = PVE::RPCEnvironment->init('cli');

$rpcenv->init_request();
$rpcenv->set_language($ENV{LANG});
$rpcenv->set_user('root@pam');

my $start_shell;

if (!GetOptions("shell" => \$start_shell)) {
    print "Usage: $0 [--shell]\n";
    exit(-1);
}

my $st = File::stat::stat("/var/cache/apt/pkgcache.bin");
if (!$st || (time() - $st->mtime) > (3 * 24 * 3600)) {

    print "\nYour package database is out of date. Please update that first.\n\n";

} else {

    my $cmdstr = 'apt-get dist-upgrade';

    print "Starting system upgrade: apt-get dist-upgrade\n";

    my $oldlist = PVE::API2::APT->list_updates({ node => $nodename });

    system('apt-get', 'dist-upgrade');

    my $pkglist = PVE::API2::APT->list_updates({ node => $nodename });

    print "\n";
    if (my $count = scalar(@$pkglist)) {
        print "System not fully up to date (found $count new packages)\n\n";
    } else {
        print "Your System is up-to-date\n\n";
    }

    my $newkernel;
    foreach my $p (@$oldlist) {
        if (
            ($p->{Package} =~ m/^(?:pve|proxmox)-kernel/)
            && !grep { $_->{Package} eq $p->{Package} } @$pkglist
        ) {
            $newkernel = 1;
            last;
        }
    }

    if ($newkernel) {
        print "\n";
        print "Seems you installed a kernel update - Please consider rebooting\n"
            . "this node to activate the new kernel.\n\n";
    }
}

if ($start_shell) {
    print "starting shell\n";
    system('/bin/bash -l');
}

exit 0;

__END__

=head1 NAME

pveupgrade - wrapper arournd "apt-get dist-upgrade"

=head1 SYNOPSIS

  pveupgrade [--shell]

=head1 DESCRIPTION

This is a small wrapper around "apt-get dist-upgrade". We use this to
print additional information (kernel restart required?), and
optionally run an interactive shell after the update (--shell)
