#!/bin/sh
exec perl -x -S $0 ${1+"$@"} # -*-perl-*-
#!perl -w
# SPDX-License-Identifier: BSD-3-Clause-CMU
# See COPYING file at the root of the distribution for more details.
#
# script to translate sieve scripts to use unixhierarchysep and/or altnamespace
# make sure you run it as the cyrus user

require 5;
use strict;
use warnings;

use Getopt::Std;

my $OPT_WasUnix = 0;
my $OPT_WasAlt  = 0;
my $imapdconf   = "/etc/imapd.conf";

my %Opts;
getopts('vnhuaC:', \%Opts);
usage() if $Opts{h};

my $OPT_NoAction = $Opts{n};
my $OPT_Verbose = $Opts{v} || $Opts{n};

my $OPT_Force   = 1 if $Opts{f};
$OPT_WasUnix    = 1 if $Opts{u};
$OPT_WasAlt     = 1 if $Opts{a};
$imapdconf      = $Opts{C} if $Opts{C};

$| = 1;

# XXX - actually read the cyrus username from the imapd.conf and
# change ownership as appropriate?
die "must not run as root" if ($< == 0);

my $sievedir = "/usr/sieve";
my $userprefix = "Other Users";
my $sharedprefix = "Shared Folders";
# The following two settings used to default to 0,but that changed
# with v3.0
my $unixhierarchysep = 1;
my $altnamespace = 1;

my @configs = ($imapdconf);

while (my $conf = shift @configs) {
    read_conf($conf);
}

sub ouch {
    my $msg = shift;

    if ($OPT_Force || $OPT_NoAction) {
        print "error: $msg\n";
    } else {
        print "fatal error: $msg\n";
        exit 1;
    }
}

sub usage {
    die <<EOF
usage: $0 [-v] [-n] [-u] [-a] [-C imapd.conf]

       -v verbose
       -n no change - just show what would be done
       -f keep going on errors
       -u previous configuration used "unixhierarchysep: yes"
       -a previous configuration used "altnamespace: yes"
       -C use configuration file specified, rather than default

NOTE: if imapd.conf is not provided, it will be read from the default
location.  On a normal system this will be /etc/imapd.conf.  The *new*
settings for unixhierarchysep and altnamespace will be read from the
provided imapd.conf.

WARNING: By default, this utility assumes that the OLD configuration
did not use either unixhierarchysep or altnamespace.  If you had used
either of these you MUST indicate this or your sieve scripts may get
broken!

In verbose mode, each command will be printed.

In "no change" mode, it will just print the changes.  Note, verbose is
always turned on in no-change mode.

NOTE: It should be safe to run translatesieve on a running system, but
it may mess things up horribly if you have some processes still running
with old config, and some with new - so it is always recommended to
fully shut down Cyrus, change the configuration file, run
translatesieve, and then start Cyrus again.
EOF
}

sub read_conf {
    my $file = shift;

    open CONF, $file or die "can't open $file";
    while (<CONF>) {
        if (/^#/) {
            next;
        }
        if (/\@include:\s+(.*)$/) {
            push @configs, $1;
        }
        if (/^sievedir:\s+(.*)$/) {
            $sievedir = $1;
            print "you are using $sievedir as your sieve directory.\n";
        }
        if (/^unixhierarchysep:\s*(0|f|no|off)/) {
            $unixhierarchysep = 0;
        }
        if (/^altnamespace:\s*(0|f|no|off)/) {
            $altnamespace = 0;
        }
        if (/^userprefix:\s*(.*)$/) {
            $userprefix = $1;
            print "you are using $userprefix as your other users prefix.\n";
        }
        if (/^sharedprefix:\s*(.*)$/) {
            $sharedprefix = $1;
            print "you are using $sharedprefix as your shared prefix.\n";
        }
    }
    close CONF;
}

# Only continue if the new settings are different from the old
unless (($unixhierarchysep != $OPT_WasUnix) || ($altnamespace != $OPT_WasAlt)) {
    ouch "There's been no change to Unix hierarchy separator or the alternate namespace";
    exit;
}

# Which separator did we used to use?
my $sep = $OPT_WasUnix ? '/' : '.';
my $psep = $OPT_WasUnix ? '/' : '\.'; # for use in patterns

# declare vars used in following loop
my $d = '';
my $file = '';
my $inbox = "[Ii][Nn][Bb][Oo][Xx]";
my $updates = 0;
my $orig = '';

print "translating sievedir $sievedir... ";
if ($unixhierarchysep > $OPT_WasUnix) {
    print "converting separator from '.' to '/'\n";
} elsif ($OPT_WasUnix > $unixhierarchysep) {
    print "converting separator from '/' to '.'\n";
} else {
    print "not converting separator.\n";
}

if ($altnamespace > $OPT_WasAlt) {
    print "converting name space from traditional to alternative.\n";
} elsif ($OPT_WasAlt > $altnamespace) {
    # Due to ambiguous results, with shared folders, we cannot convert back
    # to altnamespace: off
    ouch "this utility *cannot* convert from altnamespace to traditional!";
    exit;
} else {
    print "not changing name space.\n";
}

chdir $sievedir or die "couldn't change to $sievedir";
opendir (H, ".");
while (my $i = readdir H) {
    if ($i eq "." || $i eq "..") {
        next;
    }
    if (-d $i) {
        if (! chdir $i) {
            ouch "couldn't chdir to $i";
            next;
        }

        # translate the scripts user by user
        opendir (D, ".");
        while ($d = readdir D) {
            next if ($d =~ /^\./s);
            if (-d $d) { # Let's just skip over files, rather than bailing
                if (! chdir $d) {
                    ouch "couldn't chdir to $d";
                    next;
                }

                # translate all of the user's scripts
                opendir DIR, ".";
                while ($file = readdir DIR) {
                    next if (!($file =~ /\.script$/));

                    print "translating $file...\n" if ($OPT_Verbose);
                    if (!open(IN, $file)) {
                        ouch "cannot open $file for reading: $!";
                        next;
                    }
                    if (!$OPT_NoAction) {
                        if (!open(OUT, ">.$file")) {
                            close(IN);
                            ouch "cannot create /.$file: $!";
                            next;
                        }
                    }

                    while (<IN>) {
                        $updates = 0;
                        $orig = $_;
                        # INBOX
                        if (/\bfileinto\s+"$inbox"\s*;/) {
                            # do nothing
                        } else {
                            # Alternate namespace
                            if ($altnamespace != $OPT_WasAlt) {
                                # Personal namespace
                                if (/\bfileinto\s+"($inbox$psep[^"]*)"\s*;/) {
                                    substr($_, index($_, $1), 6) = "";
                                    $updates++;
                                }
                                # Other Users namespace
                                elsif (/\bfileinto\s+"(user$psep[^"]*)"\s*;/) {
                                    substr($_, index($_, $1), 4) = $userprefix;
                                    $updates++;
                                }
                                # Shared namespace
                                elsif (/\bfileinto\s+"([^"]*)"\s*;/) {
                                    substr($_, index($_, $1), 0) = $sharedprefix . $sep;
                                    $updates++;
                                }
                            }
                            # Hierarchy separator
                            if ($unixhierarchysep > $OPT_WasUnix) {
                                if (/\bfileinto\s+"([^"]*)"\s*;/) {
                                    substr($_, index($_, $1)) =~ s~\.~/~g;
                                    $updates++;
                                }
                            } elsif ($unixhierarchysep < $OPT_WasUnix) {
                                if (/\bfileinto\s+"([^"]*)"\s*;/) {
                                    substr($_, index($_, $1)) =~ s~/~.~g;
                                    $updates++;
                                }
                            }
                        }
                        if ($OPT_Verbose && $updates > 0) {
                            print "< $orig";
                            print "> $_";
                        }

                        print OUT $_ unless $OPT_NoAction;
                    }
                    close(IN);
                    close(OUT);

                    if (!$OPT_NoAction) {
                        rename(".$file", "$file")
                            or ouch "couldn't move .$file to $file";
                    }
                    # print "\n";
                }

                closedir DIR;
                chdir "..";
            }
        }
        closedir D;

        # back to "$sievedir"
        chdir "..";
    }
}
closedir H;
print "done\n";
