#!/usr/bin/env php
<?php

declare(strict_types=1);

use FireflyIII\Console\Commands\Correction\CreatesGroupMemberships;
use FireflyIII\Models\Role;
use FireflyIII\Repositories\User\UserRepositoryInterface;
use FireflyIII\Support\Facades\FireflyConfig;
use FireflyIII\User;
use Illuminate\Contracts\Console\Kernel as ConsoleKernel;

function log_line(string $message): void
{
    fwrite(STDOUT, $message . PHP_EOL);
}

function error_line(string $message): void
{
    fwrite(STDERR, $message . PHP_EOL);
}

function find_app_root(): string
{
    $candidates = [];
    $env_root = getenv('FIREFLY_APP_DIR') ?: '';
    if ($env_root !== '') {
        $candidates[] = $env_root;
    }
    $candidates[] = '/var/www/html';
    $candidates[] = '/var/www/firefly-iii';
    $candidates[] = '/app';

    foreach ($candidates as $candidate) {
        if (!is_dir($candidate)) {
            continue;
        }
        if (file_exists($candidate . '/vendor/autoload.php')) {
            return $candidate;
        }
    }

    return '';
}

$email = trim((string) getenv('FIREFLY_USER_EMAIL'));
$password = (string) getenv('FIREFLY_USER_PASSWORD');

if ($email === '' || $password === '') {
    error_line('missing FIREFLY_USER_EMAIL or FIREFLY_USER_PASSWORD');
    exit(1);
}

$root = find_app_root();
if ($root === '') {
    error_line('firefly app root not found');
    exit(1);
}

$autoload = $root . '/vendor/autoload.php';
$app_bootstrap = $root . '/bootstrap/app.php';

if (!file_exists($autoload) || !file_exists($app_bootstrap)) {
    error_line('firefly bootstrap files missing');
    exit(1);
}

require $autoload;
$app = require $app_bootstrap;

$kernel = $app->make(ConsoleKernel::class);
$kernel->bootstrap();

try {
    FireflyConfig::set('single_user_mode', true);
} catch (Throwable $exc) {
    error_line('failed to enforce single_user_mode: '.$exc->getMessage());
}

$repository = $app->make(UserRepositoryInterface::class);

$existing_user = User::where('email', $email)->first();
$first_user = User::count() == 0;

if (!$existing_user) {
    $existing_user = User::create(
        [
            'email' => $email,
            'password' => bcrypt($password),
            'blocked' => false,
            'blocked_code' => null,
        ]
    );

    if ($first_user) {
        $role = Role::where('name', 'owner')->first();
        if ($role) {
            $existing_user->roles()->attach($role);
        }
    }

    log_line(sprintf('created firefly user %s', $email));
} else {
    log_line(sprintf('updating firefly user %s', $email));
}

$existing_user->blocked = false;
$existing_user->blocked_code = null;
$existing_user->save();

$repository->changePassword($existing_user, $password);
CreatesGroupMemberships::createGroupMembership($existing_user);

log_line('firefly user sync complete');
