package Cpanel::Easy::Apache::Utils::OldProfile;

# cpanel - Cpanel/Easy/Apache/Utils/OldProfile.pm Copyright(c) 2014 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

use Cpanel::HttpUtils ();

sub run {
    return
      if -e '/var/cpanel/easyapache/no_ea_conf_from_old'
      || -e '/var/cpanel/easy/no_ea_conf_from_old';

    if ( !-e '/var/cpanel/easy/apache/profile/_main.yaml' ) {
        if ( -e '/var/cpanel/easyapache/EasyApacheMyConf.pm' ) {
            _make_main_yaml_from_ea2();
        }
        elsif ( -e '/etc/buildapache/config.pl' ) {
            _make_main_yaml_from_ea1();
        }
        elsif ( -e '/home/cpapachebuild/buildapache/config.pl' ) {
            _make_main_yaml_from_ea1();
        }
    }

    Cpanel::FileUtils::touchfile('/var/cpanel/easy/no_ea_conf_from_old');
}

sub _general_proc {
    my ( $v, $handler ) = @_;

    require Cpanel::Easy::PHP5;
    my @p5v_ord = Cpanel::Easy::PHP5->versions();

    my ( $php, $php5 ) = _get_php_versions( \@p5v_ord );
    my %old = _get_old_hash( $v, $php, $php5 );
    my %map = _get_map_hash( $v, $php, $php5 );

    if ( $v eq '1' ) {
        my %new = %old;
        %old = ( '1' => \%new ) if $v eq '1';
    }

    my $new_config_ref = Cpanel::DataStore::fetch_ref('/var/cpanel/easy/apache/profile/custom/cpanel_default.yaml');

    my %test = (
        'dav'          => 0,
        'php-curl-ssl' => 0,
        'expire'       => 0,
    );

  VER:
    for my $ver ( keys %map ) {
        my $opp = delete $map{$ver}->{'_opposite_boolean'};
      OPT:
        for my $opt ( keys %{ $map{$ver} } ) {
            if ( $map{$ver}->{$opt} =~ m{^NA-(.*)} && $old{$ver}->{$opt} ) {
                warn "Sorry, $1's inclusion and/or useage has changed so your old setting will not effect the new configuration.\n";
                next OPT;
            }

            next OPT if $map{$ver}->{$opt} =~ m{^NA-(.*)};
            next OPT if !exists $old{$ver}->{$opt};

            my $bool = 0;
            if ( exists $opp->{$opt} ) {
                $bool = $old{$ver}->{$opt} ? 0 : 1;
            }
            else {
                $bool = $old{$ver}->{$opt} ? 1 : 0;
            }

            $handler->( $bool, $ver, $opt, $new_config_ref, \%map, \%old );
        }
    }

    $new_config_ref->{ 'Cpanel::Easy::PHP' . $php } = 1;
    my $off_php = $php eq '5' ? '4' : '5';
    $new_config_ref->{ 'Cpanel::Easy::PHP' . $off_php } = 0;

    $new_config_ref->{ 'Cpanel::Easy::PHP5::' . $php5 } = 1;

    for my $off5 (@p5v_ord) {
        next if $off5 eq $php5;
        $new_config_ref->{ 'Cpanel::Easy::PHP5::' . $off5 } = 0;
    }

    $new_config_ref->{'Apache'}{'version'} = Cpanel::HttpUtils::get_current_apache_version_key() || 1;
    my %old_whm_addons = (
        'Cpanel::Easy::ModBandwidth' => 'modbandwidth',
        'Cpanel::Easy::ModJk5'       => 'tomcat',
        'Cpanel::Easy::ModMono'      => 'modmono',
        'Cpanel::Easy::ModSec'       => 'modsecurity',
    );

    my %installed_whm_addons;

    if ( -e '/var/cpanel/addonmodules' ) {
        if ( open my $list_fh, '<', '/var/cpanel/addonmodules' ) {
            while (<$list_fh>) {
                my $line = $_;
                chomp($line);
                $installed_whm_addons{$line}++;
            }
            close $list_fh;
        }
        else {
            warn "Could not open /var/cpanel/addonmodules, can not carry over settings: $!";
        }
    }

    for my $old_whm_addon ( keys %old_whm_addons ) {
        $new_config_ref->{$old_whm_addon} = exists $installed_whm_addons{ $old_whm_addons{$old_whm_addon} } ? 1 : 0;
    }

    Cpanel::DataStore::store_ref( '/var/cpanel/easy/apache/profile/_main.yaml', $new_config_ref );
}

sub _make_main_yaml_from_ea1 {

    # create '/var/cpanel/easy/apache/profile/_main.yaml'
    # from '/home/cpapachebuild/buildapache/config.pl'
    # as per http://httpupdate.cpanel.net/cpanelsync/EDGE/scripts/ea_conf_from_old.bz2 (orig script is gone)

    _general_proc(
        1,
        sub {
            my ( $bool, $ver, $opt, $new_config_ref, $map_hr, $old_hr ) = @_;

            my $new = $map_hr->{$ver}{$opt};
            return if !$new;

            if ( $new =~ m{::} ) {
                $new_config_ref->{$new} = $bool;
            }
            else {
                $new_config_ref->{'Apache'}{'optmods'}{$new} = $bool;
            }
        },
    );
}

sub _make_main_yaml_from_ea2 {

    # create '/var/cpanel/easy/apache/profile/_main.yaml'
    # from '/var/cpanel/easyapache/EasyApacheMyConf.pm'

    _general_proc(
        2,
        sub {
            my ( $bool, $ver, $opt, $new_config_ref, $map_hr, $old_hr ) = @_;

            my $new = $map_hr->{$ver}{$opt};
            return if !$new;

            if ( $new =~ m{::} ) {
                $new_config_ref->{$new} = $bool;
            }
            else {
                $new_config_ref->{'Apache'}{'optmods'}{$new} = $bool;
            }
        },
    );
}

#################
#### functions ##
#################

sub _get_php_versions {
    my ($p5_ar) = @_;
    my @p5v_ord = @{$p5_ar};

    my $php = '';
    if ( open my $phpver_fh, '<', '/usr/local/apache/conf/php.version' ) {
        $php = <$phpver_fh>;
        close $phpver_fh;
        chomp $php;
    }
    else {
        warn "Could not open php.version file: $!";
    }

    if ( $php !~ m{^\d+\.\d+\.\d+$} ) {
        warn "Could not determine PHP version from php.version file, defaulting to $p5v_ord[-1]";
        $php = $p5v_ord[-1];
    }

    $php =~ s{\.}{\_}g;

    my ($pv) = $php =~ m{^(\d)_};

    $php =~ s{^\d_}{};

    if ( $pv eq '5' ) {
        my %p5v;
        @p5v{@p5v_ord} = ();
        if ( !exists $p5v{$php} ) {
            warn "PHP $php is not available in the new easyapache. Defaulting to latest php5";
            $php = $p5v_ord[-1];
        }
    }
    else {
        warn "Could not determine if PHP was 4 or 5 defaulting to $p5v_ord[-1]";
        $php = $p5v_ord[-1];
    }

    my $php5 = $pv eq '5' ? $php : $p5v_ord[-1];

    return ( $pv, $php5 );
}

sub _get_map_hash {
    my ( $v, $php, $php5 ) = @_;
    if ( $v eq '2' ) {
        return _get_ea2_map_hash( $php, $php5 );
    }
    elsif ( $v eq '1' ) {
        return _get_ea1_map_hash( $php, $php5 );
    }
}

sub _get_old_hash {
    my ( $v, $php, $php5 ) = @_;
    if ( $v eq '2' ) {
        return _get_ea2_hash( $php, $php5 );
    }
    elsif ( $v eq '1' ) {
        return _get_ea1_hash( $php, $php5 );
    }
}

sub _get_ea1_hash {
    my ( $php, $php5 ) = @_;
    my %SETMODULE;
    my $conf = '';

    my $file =
      -e '/etc/buildapache/config.pl'
      ? '/etc/buildapache/config.pl'
      : '/home/cpapachebuild/buildapache/config.pl';

    if ( open my $conf_fh, '<', $file ) {
        while ( readline $conf_fh ) {
            $conf .= $_;
        }
        close $conf_fh;
        eval $conf;
    }

    return %SETMODULE;
}

sub _get_ea2_hash {
    my ( $php, $php5 ) = @_;
    require '/var/cpanel/easyapache/EasyApacheMyConf.pm';
    return %EasyApacheMyConf::saved_configuration;
}

sub _get_ea1_map_hash {
    my ( $php, $php5 ) = @_;

    #  'ea1 ap1 opt' => 'ea3 ap1 opt',

    $php = 'Cpanel::Easy::PHP5';

    my %ea1 = (
        '1' => {
            '_opposite_boolean' => {
                'rewrite'      => 'Cpanel::Easy::Apache::Rewrite',
                'auth'         => 'Cpanel::Easy::Apache::Auth',
                'imap'         => 'Cpanel::Easy::Apache::Imap',
                'authbasic'    => 'Cpanel::Easy::Apache::AuthBasic',
                'authzdefault' => 'Cpanel::Easy::Apache::AuthzDefault',
                'authndefault' => 'Cpanel::Easy::Apache::AuthnDefault',
                'authzhost'    => 'Cpanel::Easy::Apache::AuthzHost',
                'authzuser'    => 'Cpanel::Easy::Apache::AuthzUser',
                'mime'         => 'Cpanel::Easy::Apache::Mime',
                'access'       => 'Cpanel::Easy::Apache::Access',
                'actions'      => 'Cpanel::Easy::Apache::Actions',
                'alias'        => 'Cpanel::Easy::Apache::Alias',
                'asis'         => 'Cpanel::Easy::Apache::Asis',
                'auth'         => 'Cpanel::Easy::Apache::Auth',
                'autoindex'    => 'Cpanel::Easy::Apache::Autoindex',
                'cgi'          => 'Cpanel::Easy::Apache::CGI',
                'cgid'         => 'Cpanel::Easy::Apache::CGId',
                'dir'          => 'Cpanel::Easy::Apache::DIR',
                'env'          => 'Cpanel::Easy::Apache::Env',
                'include'      => 'Cpanel::Easy::Apache::Include',
                'logconfig'    => 'Cpanel::Easy::Apache::LogConfig',
                'negotiation'  => 'Cpanel::Easy::Apache::Negotiation',
                'setenvif'     => 'Cpanel::Easy::Apache::Setenvif',
                'userdir'      => 'Cpanel::Easy::Apache::Userdir',

            },
            'attach'     => 'NA-attach',
            'auth_mysql' => 'NA-auth_mysql',
            'bwprotect'  => 'NA-bwprotect',
            'bytes'      => 'NA-bytes',
            'dav'        => 'Dav',
            'expire'     => 'Expires',
            'fdsetsize'  => 'RaiseFDSetsize',
            'limit'      => 'RaiseHardServerLimit',
            'perl'       => 'Cpanel::Easy::ModPerl',

            'php-bcmath'      => $php . '::Bcmath',
            'php-cal'         => $php . '::Calendar',
            'php-curl'        => $php . '::Curl',
            'php-curl-ssl'    => $php . '::CurlSSL',
            'php-exif'        => $php . '::Exif',
            'php-ftp'         => $php . '::FTP',
            'php-gd'          => $php . '::GD',
            'php-gd-ttf'      => 'NA-php-gd-ttf',
            'php-gettext'     => $php . '::Gettext',
            'php-imap'        => $php . '::Imap',
            'php-mbstring'    => $php . '::Mbstring',
            'php-mcrypt'      => $php . '::Mcrypt',
            'php-mhash'       => $php . '::Mhash',
            'php-mk'          => $php . '::MagicQuotes',
            'php-mm'          => $php . '::MM',
            'php-mysql'       => $php =~ m{5$} ? $php . '::Mysql' : 'NA- PHP 4 Mysql',
            'php-net-snmp'    => $php . '::SNMP',
            'php-openssl'     => $php . '::Openssl',
            'php-pathdiscard' => $php . '::DiscardPath',
            'php-pear'        => 'NA-with-pear',
            'php-pg'          => $php . '::Pgsql',
            'php-pspell'      => $php . '::Pspell',
            'php-safe'        => $php . '::SafeMode',
            'php-sockets'     => $php . '::Sockets',
            'php-sysmysql'    => $php . '::MysqlOfSystem',
            'php-trackvars'   => 'NA-trackvars',
            'php-ttf'         => $php . '::TTF',
            'php-vs'          => $php . '::Versioning',
            'php-wddx'        => $php . '::Wddx',
            'php-xmlrpc'      => $php . '::XmlRPC',
            'php-zlib'        => $php . '::Zlib',

            'phpsuexec' => 'PHPAsUser',
            'rewrite'   => 'Rewrite',
            'roaming'   => 'NA-roaming',
            ''          => 'NA-blank',
            'ssl'       => 'NA-Openssl',
            'throttle'  => 'NA-throttle',
        },
    );

    return %ea1;
}

sub _get_ea2_map_hash {
    my ( $php, $php5 ) = @_;

    #  'ea1 ap1 opt' => 'ea3 ap1 opt',

    $php5 = '5_' . $php5;
    $php  = $php5;

    $php  = "XPHP__$php\__S";
    $php5 = "XPHP__$php5\__S";

    my %map;
    my %map_php = (
        "${php5}::Apply_Function_Security__S" => 'Cpanel::Easy::PHP5::SafePHPCGI',
        "${php5}::Apply_Hardening_Patch__S"   => 'Cpanel::Easy::PHP5::HardPHP',
        "${php5}::Disable_Mbregex"            => 'Cpanel::Easy::PHP5::Mbregex',
        "${php5}::Enable_Bcmath"              => 'Cpanel::Easy::PHP5::BcMath',
        "${php5}::Enable_Calendar"            => 'Cpanel::Easy::PHP5::Calendar',
        "${php5}::Enable_Cgi"                 => 'Cpanel::Easy::PHP5::CGI',
        "${php5}::Enable_Dbase"               => 'Cpanel::Easy::PHP5::Dbase',
        "${php5}::Enable_Discard_Path"        => 'Cpanel::Easy::PHP5::DiscardPath',
        "${php5}::Enable_Embedded_Mysqli__S"  => 'Cpanel::Easy::PHP5::Mysqli',
        "${php5}::Enable_Exif"                => 'Cpanel::Easy::PHP5::Exif',
        "${php5}::Enable_Fastcgi"             => 'Cpanel::Easy::PHP5::Fastcgi',
        "${php5}::Enable_Force_Cgi_Redirect"  => 'Cpanel::Easy::PHP5::ForceCGIRedirect',
        "${php5}::Enable_Magic_Quotes"        => 'Cpanel::Easy::PHP5::MagicQuotes',
        "${php5}::Enable_Mbstring"            => 'Cpanel::Easy::PHP5::Mbstring',
        "${php5}::Enable_Memory_Limit__S"     => 'Cpanel::Easy::PHP5::MemoryLimit',
        "${php5}::Enable_PDO__S"              => 'Cpanel::Easy::PHP5::PDO',
        "${php5}::Enable_Safe_Mode"           => 'Cpanel::Easy::PHP5::SafeMode',
        "${php5}::Enable_Sockets"             => 'Cpanel::Easy::PHP5::Sockets',
        "${php5}::Enable_Versioning"          => 'Cpanel::Easy::PHP5::Versioning',
        "${php5}::Enable_Wddx"                => 'Cpanel::Easy::PHP5::Wddx',
        "${php5}::Enable_Zend_Multibyte"      => 'Cpanel::Easy::PHP5::ZendMultibyte',
        "${php5}::With_Bz2"                   => 'Cpanel::Easy::PHP5::Bz2',
        "${php5}::With_Curl"                  => 'Cpanel::Easy::PHP5::Curl',
        "${php5}::With_Curl_SSL_Support"      => 'Cpanel::Easy::PHP5::CurlSSL',
        "${php5}::With_Curlwrappers"          => 'Cpanel::Easy::PHP5::Curlwrappers',
        "${php5}::With_GD"                    => 'Cpanel::Easy::PHP5::GD',
        "${php5}::With_Gettext"               => 'Cpanel::Easy::PHP5::Gettext',
        "${php5}::With_Imap__S"               => 'Cpanel::Easy::PHP5::Imap',
        "${php5}::With_Mcrypt"                => 'Cpanel::Easy::PHP5::Mcrypt',
        "${php5}::With_Mhash"                 => 'Cpanel::Easy::PHP5::Mhash',
        "${php5}::With_Mime_Magic"            => 'Cpanel::Easy::PHP5::MimeMagic',
        "${php5}::With_MM"                    => 'Cpanel::Easy::PHP5::MM',
        "${php5}::With_Mysql_Of_System"       => 'Cpanel::Easy::PHP5::MysqlOfSystem',
        "${php5}::With_Mysql"                 => 'Cpanel::Easy::PHP5::Mysql',
        "${php5}::With_OpenSSL"               => 'Cpanel::Easy::PHP5::Openssl',
        "${php5}::Without_Iconv"              => 'Cpanel::Easy::PHP5::WithoutIconv',
        "${php5}::Without_Pcre_Regex"         => 'NA- PHP 5 PcreRegex',
        "${php5}::Without_Pear"               => 'Cpanel::Easy::PHP5::Pear',
        "${php5}::With_Pgsql__S"              => 'Cpanel::Easy::PHP5::Pgsql',
        "${php5}::With_Pspell"                => 'Cpanel::Easy::PHP5::Pspell',
        "${php5}::With_SNMP__S"               => 'Cpanel::Easy::PHP5::SNMP',
        "${php5}::With_SOAP"                  => 'Cpanel::Easy::PHP5::SOAP',
        "${php5}::With_Tidy"                  => 'Cpanel::Easy::PHP5::Tidy',
        "${php5}::With_TTF"                   => 'Cpanel::Easy::PHP5::TTF',
        "${php5}::With_Xmlrpc"                => 'Cpanel::Easy::PHP5::XmlRPC',
        "${php5}::With_XSL__S"                => 'Cpanel::Easy::PHP5::XSL',
        "${php5}::With_Zlib__S"               => 'Cpanel::Easy::PHP5::Zlib',
    );

    $map{'1'} = {
        q
	    '_opposite_boolean' => {
            "${php5}::Mbregex"           => 'Cpanel::Easy::PHP5::Mbregex',
            'Apache::Disable_Rewrite__S' => 'Rewrite',
        },

        %map_php,

        'Apache::Disable_Rewrite__S'  => 'Rewrite',
        'Apache::Enable_Auth_anon'    => 'AuthAnon',
        'Apache::Enable_Auth_dbm'     => 'AuthDBM',
        'Apache::Enable_Auth_db'      => 'AuthDB',
        'Apache::Enable_Auth_digest'  => 'AuthDigest',
        'Apache::Enable_Cern_meta'    => 'CernMeta',
        'Apache::Enable_Expires'      => 'Expires',
        'Apache::Enable_Headers'      => 'Headers',
        'Apache::Enable_Info'         => 'Info',
        'Apache::Enable_Log_agent'    => 'LogAgent',
        'Apache::Enable_Log_forensic' => 'LogForensic',
        'Apache::Enable_Log_referer'  => 'LogReferer',
        'Apache::Enable_Mime_magic'   => 'MimeMagic',
        'Apache::Enable_Mmap_static'  => 'MmapStatic',
        'Apache::Enable_Speling'      => 'Speling',
        'Apache::Enable_Unique_id'    => 'UniqueId',
        'Apache::Enable_Usertrack'    => 'Usertrack',

        'XMod_DAV__S'                                => 'Dav',
        'XMod_Perl__S'                               => 'Cpanel::Easy::ModPerl',
        'XphpSUExec'                                 => 'PHPAsUser',
        'XPrevent_Users_from_reading_other_webroots' => 'Fileprotect',
        'XRaise_FD_SETSIZE_to_16384'                 => 'RaiseFDSetsize',
        'XRaise_HARD_SERVER_LIMIT'                   => 'RaiseHardServerLimit',
    };

    $map{'2'} = {
        '_opposite_boolean' => {
            "${php5}::Mbregex"             => 'Cpanel::Easy::PHP5::Mbregex',
            'Apache::Disable_Access'       => 'Access',
            'Apache::Disable_Actions'      => 'Actions',
            'Apache::Disable_Alias'        => 'Alias',
            'Apache::Disable_Asis'         => 'Asis',
            'Apache::Disable_Auth'         => 'Auth',
            'Apache::Disable_Autoindex'    => 'Autoindex',
            'Apache::Disable_Cgid'         => 'Cgid',
            'Apache::Disable_Cgi'          => 'CGI',
            'Apache::Disable_Charset_Lite' => 'CharsetLite',
            'Apache::Disable_Dav__S'       => 'Dav',
            'Apache::Disable_Dir'          => 'DIR',
            'Apache::Disable_Env'          => 'Env',
            'Apache::Disable_Imap'         => 'Imap',
            'Apache::Disable_Include'      => 'Include',
            'Apache::Disable_Log_Config'   => 'LogConfig',
            'Apache::Disable_Negotiation'  => 'Negotiation',
            'Apache::Disable_Rewrite__S'   => 'Rewrite',
            'Apache::Disable_Setenvif'     => 'Setenvif',
            'Apache::Disable_Status'       => 'Status',
            'Apache::Disable_Userdir'      => 'Userdir',
        },

        %map_php,

        'Apache::Disable_Access'         => 'Access',
        'Apache::Disable_Actions'        => 'Actions',
        'Apache::Disable_Alias'          => 'Alias',
        'Apache::Disable_Asis'           => 'Asis',
        'Apache::Disable_Auth'           => 'Auth',
        'Apache::Disable_Autoindex'      => 'Autoindex',
        'Apache::Disable_Cgid'           => 'Cgid',
        'Apache::Disable_Cgi'            => 'CGI',
        'Apache::Disable_Charset_Lite'   => 'CharsetLite',
        'Apache::Disable_Dav__S'         => 'Dav',
        'Apache::Disable_Dir'            => 'DIR',
        'Apache::Disable_Env'            => 'Env',
        'Apache::Disable_Imap'           => 'Imap',
        'Apache::Disable_Include'        => 'Include',
        'Apache::Disable_Log_Config'     => 'LogConfig',
        'Apache::Disable_Negotiation'    => 'Negotiation',
        'Apache::Disable_Rewrite__S'     => 'Rewrite',
        'Apache::Disable_Setenvif'       => 'Setenvif',
        'Apache::Disable_Status'         => 'Status',
        'Apache::Disable_Userdir'        => 'Userdir',
        'Apache::Enable_Auth_Anon'       => 'AuthAnon',
        'Apache::Enable_Auth_Dbm'        => 'AuthDBM',
        'Apache::Enable_Auth_Digest'     => 'AuthDigest',
        'Apache::Enable_Auth_Ldap'       => 'LDAP',
        'Apache::Enable_Cern_Meta'       => 'CernMeta',
        'Apache::Enable_Charset_Lite'    => 'CharsetLite',
        'Apache::Enable_Deflate'         => 'Deflate',
        'Apache::Enable_Disk_Cache'      => 'DiskCache',
        'Apache::Enable_Expires'         => 'Expires',
        'Apache::Enable_Ext_Filter'      => 'ExtFilter',
        'Apache::Enable_File_Cache'      => 'FileCache',
        'Apache::Enable_Headers'         => 'Headers',
        'Apache::Enable_Info'            => 'Info',
        'Apache::Enable_Isapi'           => 'NA-Isapi',
        'Apache::Enable_Ldap'            => 'LDAP',
        'Apache::Enable_Mem_Cache'       => 'MemCache',
        'Apache::Enable_Mime_Magic'      => 'MimeCache',
        'Apache::Enable_Speling'         => 'Speling',
        'Apache::Enable_Unique_Id'       => 'UniqueId',
        'Apache::Enable_Usertrack'       => 'Userdir',
        'Apache::With_MPM_Beos__S'       => 'MPMBeOS',
        'Apache::With_MPM_Leader__S'     => 'MPMLeader',
        'Apache::With_MPM_Mpmt_os2__S'   => 'MPMOS2',
        'Apache::With_MPM_Perchild__S'   => 'MPMBeOS',
        'Apache::With_MPM_Prefork__S'    => 'MPMPrefork',
        'Apache::With_MPM_Threadpool__S' => 'MPMThreadpool',
        'Apache::With_MPM_Worker__S'     => 'MPMWorker',

        'XModules_for_developers__S'                 => 'NA-XModules_for_developers__S',
        'XPrevent_Users_from_reading_other_webroots' => 'Fileprotect',
        'YMod_Perl__S'                               => 'Cpanel::Easy::ModPerl',
        'YMod_suPHP__S'                              => 'PHPAsUser',
    };

    $map{'2_2'} = $map{'2'};

    return %map;
}

1;
