#!/usr/bin/perl

# cpanel - atmailopen/install                     Copyright(c) 2012 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cpanel license. Unauthorized copying is prohibited

use strict;
use warnings;

use lib '/usr/local/cpanel';
use Cpanel::ExtractFile     ();
use Cpanel::FileUtils::Copy ();
use Cpanel::DataStore       ();
use Cwd;

my $DIR         = '/usr/local/cpanel/base/3rdparty';
my $atmail_base = "$DIR/atmailopen";

# This is the installer script for the atmail open webmail client.

my $min_version = '11.25.1';

# Check cpanel version
if ( get_cpanel_version() < _numerical_version($min_version) ) {
    print "This plugin requires a cPanel with custom webmail applications enabled, $min_version or later.\n";
    exit(1);
}

# make sure webmail dir exists
my $webmail = '/var/cpanel/webmail';
mkdir $webmail if ( !-d $webmail );
if ( !-d $webmail ) {
    print "Cannoty create directory $webmail\n";
    exit(1);
}

my $atmailopen_version    = '1.0.5';
my $internal_version      = 'cp0';
my $atmail_cpanel_version = "$atmailopen_version.$internal_version";
my $versionfile           = '/var/cpanel/version/atmailopen';

# Extract Tarball
print "Extracting source files\n";

my $file_list = Cpanel::ExtractFile::extractfile( "atmailopen-$atmailopen_version.tgz", 'dir' => $DIR );
fail('Could not extract atmailopen.tgz') if ref $file_list ne 'ARRAY';

# Apply patches
print "Applying patches\n";

# no need to quotemeta() $atmail_base since it is hard coded above and unmodifed i.e. it should be safe
foreach my $patch ( glob("patches/*.patch") ) {
    system("patch -d $atmail_base -p1 < $patch") == 0 or print "patch $patch had issues and exited w/ $?\n";
}

# copy config.php.in to config.php
print "Putting config in place\n";
Cpanel::FileUtils::Copy::safecopy( "$atmail_base/libs/Atmail/Config.php.default", "$atmail_base/libs/Atmail/Config.php" ) || fail("Could not copy configuration file over: $!");

# copy logo
print "Copying logo into place\n";
Cpanel::FileUtils::Copy::safecopy( 'atmail.gif', $atmail_base ) || fail("Could not copy logo into $atmail_base: $!");
Cpanel::FileUtils::Copy::safecopy( 'spinner.gif', "$atmail_base/imgs/spinner.gif" ) || print "Unable to copy spinner.gif into place\n";

# create webmail registeration file
print "Writing webmail configuration files\n";

my $webmail_conf = {
    'url'         => '/3rdparty/atmailopen/index.php',
    'displayname' => 'Atmail Open',
    'icon'        => '/3rdparty/atmailopen/atmail.gif',
};

Cpanel::DataStore::store_ref( '/var/cpanel/webmail/webmail_atmailopen.yaml', $webmail_conf ) || fail("could not write webmail configuration file: $!");

sub fail {
    my ($msg) = @_;
    print $msg . "\nUninstalling ...\n\n";
    system('sh uninstall');
    exit(0);
}

# This is in here for future-proofing purposes
if ( open( my $vh_fh, '>', $versionfile ) ) {
    print {$vh_fh} $atmail_cpanel_version;
    close($vh_fh);
}
else {
    print "Could not write version file\n";
}

print "atmailopen updated to $atmail_cpanel_version\n";
exit(0);

# this plugin can be used on any cpanel version
#   we cannot rely on all cPanel modules
sub get_cpanel_version {
    my $cp_exec;

    foreach my $candidate (qw{/usr/local/cpanel/cpanel /usr/local/cpanel/cpanel.pl}) {
        -x $candidate and $cp_exec = $candidate and last;
    }
    print "Cannot find cPanel on your server" and exit(1) unless $cp_exec;
    my $full = `$cp_exec -V`;
    if ( $full =~ /^\s*([\d\.]+)/ ) {
        return _numerical_version($1);
    }
    return 0;
}

sub _numerical_version {
    my $version = shift || 0;
    my ( $major, $minor, $release ) = split( /\./, $version, 3 );
    return sprintf( "%d%02d%02d", int( $major || 0 ), int( $minor || 0 ), int( $release || 0 ) );
}
