#!/usr/bin/perl -T

$ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';

delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};

use strict;
use warnings;

use PVE::SafeSyslog;
use PVE::Service::pveproxy;

$SIG{'__WARN__'} = sub {
    my $err = $@;
    my $t = $_[0];
    chomp $t;
    print STDERR "$t\n";
    syslog('warning', "%s", $t);
    $@ = $err;
};

my $prepare = sub {
    my $rundir = "/var/run/pveproxy";
    if (mkdir($rundir, 0700)) { # only works at first start if we are root)
        my $gid = getgrnam('www-data') || die "getgrnam failed - $!\n";
        my $uid = getpwnam('www-data') || die "getpwnam failed - $!\n";
        chown($uid, $gid, $rundir);
    }

    # Pre-create the accept-lock file as root and hand it to www-data, so that
    # the open(">>...") inside PVE::Service::pveproxy::init() succeeds even
    # after PVE::Daemon::setup has dropped privileges to www-data. Required on
    # distributions where /run/lock is not world-writable (e.g. openEuler /
    # RHEL derivatives, where the Debian default of 1777 is not in place).
    my $lock = "/var/lock/pveproxy.lck";
    my $gid = getgrnam('www-data') || die "getgrnam failed - $!\n";
    my $uid = getpwnam('www-data') || die "getpwnam failed - $!\n";
    if (open(my $fh, '>>', $lock)) {
        close($fh);
        chown($uid, $gid, $lock);
        chmod(0644, $lock);
    }
};

PVE::Service::pveproxy->run_cli_handler(prepare => $prepare);
