#!/usr/bin/perl

use v5.36;

use strict;
use warnings;

# lookup for comment signs for different languages
my %CommentSignLookup = (
    'pl'  => '#',
    'pm'  => '#',
    'tt'  => '#',
    'js'  => '//',
    'css' => '/*',
    't'   => '#',
    'xml' => '<!--',
);

# fetch and process directory argument
my %ArgumentsHash = @ARGV;

exit unless $ArgumentsHash{'--path'};

# extract path to package (assuming the package is located in /opt/otobo/)
if ( $ArgumentsHash{'--path'} =~ m|(\/opt\/otobo\/\w+?\/)| || '' ) {

    my $PackagePath = $1 || '';

    my ( $CommentStartSign, $CommentEndSign ) = ( '#', '' );
    if ( $ArgumentsHash{'--path'} =~ m|\.(\w{2,3})$| ) {
        my $FileEnding = $1;
        $CommentStartSign = $CommentSignLookup{$FileEnding};
        if ( $FileEnding eq 'css' ) {
            $CommentEndSign = '*/';
        }
        elsif ( $FileEnding eq 'xml' ) {
            $CommentEndSign = '-->'
        }
    }

    exit unless $PackagePath;

    # fetch file list of package directory
    opendir my $package_dh, $PackagePath or die "Cannot open directory: $!";

    my @FileList = readdir $package_dh;

    closedir $package_dh;

    my $PackageName = '';

    for my $File ( @FileList ) {

        # scan for sopm file
        if ( $File =~ /.*\.sopm/ ) {
            open my $file_fh, '<', $PackagePath . $File;
            NAME:
            # scan for name tag
            while (my $Line = <$file_fh>) {
                if ( $Line =~ m|\<Name\>(\w+)\<\/Name\>| ) {
                    $PackageName = $1;
                    # print package marker
                    my $FirstLine = "$CommentStartSign RotherOSS / $PackageName $CommentEndSign";
                    $FirstLine =~ s/\s+$//;
                    my $SecondLine = "$CommentStartSign EO $PackageName $CommentEndSign";
                    $SecondLine =~ s/\s+$//;
                    my @Comments = (
                        $FirstLine,
                        $SecondLine,
                    );
                    print STDOUT join("\n", @Comments);
                    exit;
                }
            }
            close $file_fh;
        }

    }

}

print STDOUT '';
