#!/usr/bin/perl
# cpanel12 - edit_com/install                     Copyright(c) 2007 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

use lib '/usr/local/cpanel';
use strict;
use warnings;
use Cpanel::Config  ();
use Cpanel::Version ();

our @install_files;
require 'install_files.pl';

my $build = Cpanel::Version::getbuild();
if ( $build =~ m/^(?:9|10)\./ ) {
    print "Sorry, the Edit.com Plugin does not work with older builds. Please update to the latest version.\n";
    print "Install will continue, but the service will not be available.\n";
}

add_feature( 'feature' => 0, 'verbose' => 1 );

my $cpconf = Cpanel::Config::loadcpconf();
if ( !$cpconf->{'root'} || substr( $cpconf->{'root'}, 0, 1 ) ne '/' || !-e $cpconf->{'root'} . '/Cpanel.pm' ) {
    $cpconf->{'root'} = '/usr/local/cpanel';
}

foreach my $file ( @install_files ) {
    my $install_file = substr( $file, 0, 1 ) ne '/' ? $cpconf->{'root'} . '/' . $file : $file;
    die "Missing file: $file" if ( !$install_file || !-e $file );    # Sanity check

    if ( -e $install_file ) {
        unlink $install_file;
    }
    else {                                                             # mkdir
        my @dirparts = split( /\//, $install_file );
        pop @dirparts;
        my $target_dir = join( '/', @dirparts );
        die if ( !$target_dir || substr( $target_dir, 0, 1 ) ne '/' );
        if ( !-d $target_dir ) {
            system 'mkdir', '-p', $target_dir;
        }
    }

    system 'cp', '-vf', $file, $install_file;
    if ( !-e $install_file ) {
        die "Failed to install $file";
    }
}

if ( -x '/usr/local/cpanel/bin/rebuild_sprites' ) {
    system '/usr/local/cpanel/bin/rebuild_sprites';
}

print "Done\n";

sub add_feature {    # See also Cpanel::Config::add_feature
    my %args = @_;
    return if !$args{'feature'};
    $args{'value'} = $args{'value'} ? 1 : 0;

    if ( opendir my $features_dh, '/var/cpanel/features' ) {
        while ( my $file = readdir $features_dh ) {
            next if $file =~ m/^\./;
            next if $file =~ m/\.cpaddons$/;
            if ( open my $ft_fh, '+<', '/var/cpanel/features/' . $file ) {
                my $has_feature = 0;
                while ( my $line = readline $ft_fh ) {
                    if ( $line =~ m/^\Q$args{'feature'}\E=/ ) {
                        $has_feature = 1;
                        print "Feature list $file already has feature.\n" if $args{'verbose'};
                    }
                }
                if ( !$has_feature ) {
                    print {$ft_fh} "$args{'feature'}=$args{'value'}\n";
                    print "Adding $args{'feature'} to feature list $file\n" if $args{'verbose'};
                }
                close $ft_fh;
            }
        }
        closedir $features_dh;
    }
}
