#!/usr/bin/env perl

# this will install packanges accoring to hostname
# USAGE: pdspkgs: hostname [-v]
#
# package lists are in pkgs/ subdirectory, following package lists are loaded:
# - 'all'
# - 'server' if hostname stars with 'a'
# - 'graphical' if hostname starts with either pythia or pandora
# - hostname prefix, which is letter prefix of hostname (for example pandora for pandora04)
# - hostname

use warnings;
use strict;
use util;
use File::Temp;

my $verbose = $ENV{ VERBOSE };
$verbose = 1 if ( @ARGV > 1 && ($ARGV[1] eq "-v" || $ARGV[0] eq "-v") );

my $hostname = `hostname`;
chomp $hostname;
$hostname = $ARGV[0] if @ARGV >= 1;

print "HOSTNAME = $hostname\n";

if ( !defined( $hostname ) || $hostname eq "" ) {
    print "USAGE: pdspkgs hostname [-v]\n";
    exit 1;
}

my @pkgs;

for ( getkeys( $hostname ) ) {
    push( @pkgs, loadList( "pkgs", $_ ) );
}

dolog( "Will install: " . join( ", ", @pkgs ) . "\n" );

sub fail {
    print STDERR "ERROR: failed for package $_[0]\n";
}

for my $pkg ( @pkgs ) {
    if ( $pkg =~ m/^!(.*)/ ) {
        $pkg = $1;
        if ( system( "pacman -Q $pkg >& /dev/null" ) == 0 ) {
            dolog( "Uninstalling $pkg...\n" );
            system_( "pacman --noconfirm -R $pkg" ) or fail( $pkg );
        }
    } elsif ( $pkg =~ m/^:(.*)/ ) {
        $pkg = $1;
        my $builddir = File::Temp->newdir( "/tmp/_build.$pkg.XXXXXX" );
        system_( "chown pacman:pacman $builddir && rsync -r localpkg/$pkg/ $builddir/" ) or fail( $pkg );
        system_( "sudo -u pacman HOME=/srv/pacman bash -c 'cd $builddir && make build'" ) or fail( $pkg );
        dolog( "Installing $pkg from local definition" );
        system_( "cd $builddir && make install PACFLAGS=--noconfirm" ) or fail( $pkg );
    } else {
        my $echo = "";
        if ( $pkg =~ /^\|([^|]*)\|(.*)$/ ) {
            $echo = $1;
            $pkg = $2;
        }
        if ( system( "pacman -Q $pkg >& /dev/null" ) ) {
            dolog( "Installing $pkg...\n" );
            if ( $echo eq "" ) {
                system_( "pacman --needed --noconfirm -S $pkg" ) or fail( $pkg );
            } else {
                system_( "echo -e '$echo' | pacman --needed -S $pkg" ) or fail( $pkg );
            }
        }
    }
}
