#!/usr/local/cpanel/3rdparty/bin/perl
# cpanel - scripts/migrate_horde2ccs               Copyright 2019 cPanel, L.L.C.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited
package CCS::scripts::migrate_horde2ccs;

use strict;
use warnings;


use Cpanel::Binaries ();
use Cpanel::DAV::Principal ();
use Cpanel::DAV::Backend::HordeCalendar ();
use Cpanel::Config::LoadUserDomains ();
use Whostmgr::Accounts::List ();
use Cpanel::AccessIds       ();
use Cpanel::SafeRun::Object ();

use lib '/var/cpanel/perl';

use Cpanel::CCS::DBUtils  ();
use Cpanel::CCS::Userdata ();

use lib '/var/cpanel/perl5/lib';

use CCSHooks ();

exit script() unless caller;

our ( $cal_script, $con_script, $php_bin );

sub script {
    die "Must be root" if $<;
    $ENV{'REMOTE_USER'} = 'root';
    $cal_script = "/usr/local/cpanel-ccs/bin/horde_calendars2ics.php";
    $con_script = "/usr/local/cpanel-ccs/bin/horde_contacts2vcf.php";
    foreach my $sub ( 'get_binary_location', 'path' ) {
        if( my $sr = Cpanel::Binaries->can($sub) ) {
            $php_bin = $sr->('php');
        }
    }
    die "Can't find php binary location!" if !$php_bin;
    my $user_to_uuid_map = Cpanel::CCS::Userdata::get_user_uuid_map();

    foreach( @{ Whostmgr::Accounts::List::listaccts() } ) {
        my $user = $_->{'user'};
        my $user_email = "$user\@$_->{'domain'}";
        my $virtuser_to_data_map = process_user($user);

        my $dbh = Cpanel::CCS::DBUtils::get_dbh();
        print "[DEBUG] Importing exported calendars & contacts to CCS for $user and associated sub-users...\n" if $ENV{'CCS_DEBUG'};

        foreach my $virt_user ( keys( %$virtuser_to_data_map ) ) {
            my $uuid = $user_to_uuid_map->{$virt_user};
            foreach my $type ( qw{calendars contacts} ) {
                print "        Processing $type for $virt_user...\n" if $ENV{'CCS_DEBUG'};
                my $resource_id = CCSHooks::insert_collection_if_needed_for_type( $type, $dbh, $uuid );
                my $text = $virtuser_to_data_map->{$virt_user}{$type};
                CCSHooks::do_inserts_for_type( $type, $dbh, \$text, $resource_id, $uuid ) if $text;
            }
        }
    }

    return 0;
}

sub process_user {
    my ( $user ) = @_;

    # Discard the info messages, etc. from logger
    my $mailusers_data;
    $mailusers_data = Cpanel::CCS::Userdata::_list_pops_for_user_with_extra_sauce($user);
    my @mailusers = keys(%$mailusers_data);
    my $qqq = join( ', ', map { '?' } 1 .. scalar(@mailusers) + 1 );
    my $query = "SELECT share_owner, share_name FROM kronolith_shares WHERE share_owner IN ( $qqq );";
    my $getter_cr = sub {
        print "[DEBUG] Exporting all Horde calendars for $user and associated sub-users...\n" if $ENV{'CCS_DEBUG'};

        my $dbh = Cpanel::DAV::Backend::DB::Horde::get_dbh();

        my ( $matches, $exception ) = Cpanel::DAV::Backend::DB::Horde::select_all(
            $dbh, $query,
            $user,
            @mailusers,
        );
        die $exception if $exception;

        my %out_hash;
        foreach my $match ( @$matches ) {
            print "        Processing $match->{'share_owner'}:$match->{'share_name'}...\n" if $ENV{'CCS_DEBUG'};
            my $input = "$match->{'share_owner'}:$match->{'share_name'}";

            # XXX I still haven't figured out how to properly pop all horde caches
            # Inside the php script, so I have to fork for every calendar right now
            my $run_res = Cpanel::SafeRun::Object->new_or_die(
                'stdin'   => $input,
                'program' => $php_bin,
                'args'    => [ $cal_script ],
                'user'    => $user,
            );
            $out_hash{$match->{'share_owner'}} = { 'calendars' => $run_res->stdout() };
        }

        print "[DEBUG] Exporting all Horde contacts for $user and associated sub-users...\n" if $ENV{'CCS_DEBUG'};

        # Now get their contacts
        foreach my $virtuser ( $user, @mailusers ) {
            print "        Processing $virtuser...\n" if $ENV{'CCS_DEBUG'};
            my $input = "$virtuser";

            my $run_res = Cpanel::SafeRun::Object->new_or_die(
                'stdin'   => $input,
                'program' => $php_bin,
                'args'    => [ $con_script ],
                'user'    => $virtuser,
            );
            $out_hash{$virtuser}{'contacts'} = $run_res->stdout();
        }

        return \%out_hash;
    };

    return Cpanel::AccessIds::do_as_user( $user, $getter_cr );
}

1;
