#!/usr/bin/perl
# cpanel - shabang-tool                              Copyright 2018 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

use strict;
use warnings;

=encoding utf-8

=head1 NAME

shabang-tool - Alter the shabang line of a perl script to unset PERL5LIB

=head1 SYNOPSIS

    shabang-tool <script>

=head1 DESCRIPTION

For history see CPANEL-18856

=cut

my $MAGIC_SHABANG = <<'EOM';
#!/bin/sh
unset PERL5LIB
eval 'if [ -x /usr/bin/perl ]; then exec /usr/bin/perl -x -- $0 ${1+"$@"}; else exec /usr/bin/env perl -x $0 ${1+"$@"}; fi;'
  if 0;
 
#!/usr/bin/perl
EOM

my $script = $ARGV[0];

if ( !$script ) {
    die "Usage: $0 <script>";
}

my $fh;
if ( !open( $fh, '<', $script ) ) {
    die "open($script): $!";
}

my @contents = <$fh>;

if ( $contents[0] =~ m{/bin/sh} ) {
    print "$script has already been modified\n";
    exit(0);
}
close($fh);

my $tmp = "$script.shabang-tool." . $$ . '.' . time();
if ( !open( $fh, '>', $tmp ) ) {
    die "open($tmp): $!";
}

$contents[0] = $MAGIC_SHABANG;
print {$fh} join( '', @contents );
close($fh);

chmod( 0755, $tmp );

rename( $tmp, $script ) or die "rename($tmp,$script): $!";

exit(0);

