#!/usr/bin/php
<?php

define('PHPWG_ROOT_PATH', dirname($argv[0]) . '/');
include(PHPWG_ROOT_PATH . 'include/config_default.inc.php');
@include(PHPWG_ROOT_PATH. 'local/config/config.inc.php');
defined('PWG_LOCAL_DIR') or define('PWG_LOCAL_DIR', 'local/');
define('DEFAULT_PREFIX_TABLE', 'piwigo_');
include(PHPWG_ROOT_PATH.PWG_LOCAL_DIR .'config/database.inc.php');
include(PHPWG_ROOT_PATH . 'include/dblayer/functions_'.$conf['dblayer'].'.inc.php');
include(PHPWG_ROOT_PATH . 'include/functions.inc.php');
include(PHPWG_ROOT_PATH . 'admin/include/functions_install.inc.php');
include(PHPWG_ROOT_PATH . 'admin/include/functions_upgrade.php');
include(PHPWG_ROOT_PATH . 'include/constants.php');
include(PHPWG_ROOT_PATH . 'include/ws_functions/pwg.extensions.php');
include(PHPWG_ROOT_PATH . 'include/template.class.php');
$filename = PHPWG_ROOT_PATH . 'plugins/OpenIdConnect/main.inc.php';

if (is_file($filename))
{
  include($filename);
  $OIDC_INSTALLED = true;
}
else
{
  $OIDC_INSTALLED = false;
};

// all namespaces with options
$namespaces_data = array('db:install' => array('language:'),
                         'user:create' => array('login:', 'mail_address:'),
                         'user:admin:create' => array('login:', 'admin_pass:', 'mail_address:', 'language:'),
                         'config:show' => array(),
                         'config:modify' => array('conf_name:', 'value:', 'type:'),
                         'config:show:array' => array('conf_name:'),
                         'config:modify:array' => array('conf_name:', 'key:', 'value:', 'type:'),
                         'config:show:json' => array('conf_name:'),
                         'config:modify:json' => array('conf_name:', 'key:', 'value:', 'type:'),
                         'plugin:activate' => array('plugin_name:'),
                         'plugin:deactivate' => array('plugin_name:'),
                         'theme:activate' => array('theme_name:'),
);
if ($OIDC_INSTALLED) {
  $namespaces_data['user:create'][] = 'oidc';
}
if (is_file(PHPWG_ROOT_PATH . 'plugins/community/admin.php')) {
  $namespaces_data['community:permission:add'] = array('type:', 'user_album', 'recursive', 'create_subcategories', 'moderated');
}

// command line must starts with -c namespace
$namespaces = array_keys($namespaces_data);
if ($argc < 3 || $argv[1] != '-c' || !in_array($argv[2], $namespaces)) {
  $namespaces_str = implode('|', $namespaces);
  exit("Usage: $argv[0]: -c [$namespaces_str]" . PHP_EOL);
}

// load extra parameter for this namespace
$namespace = $argv[2];
$rest_index = 0;
$options = getopt('c:', $namespaces_data[$namespace], $rest_index);

$error = false;
$namespace_options = '';
foreach ($namespaces_data[$namespace] as $parameter) {
  if(str_ends_with($parameter, ':')) {
    $parameter = substr($parameter, 0, -1);
    $namespace_options .= " --$parameter <$parameter>";
    if (!isset($options[$parameter])) {
      $error = true;
    }
  } else {
    $namespace_options .= " --$parameter";
  }
}
if ($rest_index != count($argv)) {
  exit("Error in arguments.". PHP_EOL . "Usage: $argv[0]: -c $namespace$namespace_options" . PHP_EOL);
}
if ($error) {
  exit("Some arguments are missing.". PHP_EOL . "Usage: $argv[0]: -c $namespace$namespace_options" . PHP_EOL);
}

function get_all_languages()
{
  include(PHPWG_ROOT_PATH . 'admin/include/languages.class.php');
  return new languages('utf-8');
}

function validate_language($language, $languages) {
  $languages_available = array_keys($languages->fs_languages);
  if (!in_array($language, $languages_available))
  {
    exit("Invalid language $language (not in " . implode(', ', $languages_available) . ") ". PHP_EOL . "Usage: $argv[0]: -c $namespace$namespace_options" . PHP_EOL);
  }
}

function cast_value($type, $value)
{
  if ($type === 'boolean')
  {
    $value = get_boolean($value);
  }
  else if ($type === 'integer')
  {
    $value = intval($value);
  }
  return $value;
}

function custom_array_modify($ori_config, $options)
{
  $value = cast_value($options['type'], $options['value']);
  $keys = array_reverse(explode('.', $options['key']));
  $update = Array($keys[0] => $value);
  for ($i=0; $i<count($keys)-1; $i++)
  {
    $update = Array($keys[$i+1] => $update);
  }
  return array_replace_recursive($ori_config, $update);
}

$errors = array();
install_db_connect($conf['db_host'], $conf['db_user'], $conf['db_password'], $conf['db_base'], $errors);
if ( count( $errors ) !== 0 )
{
  for ($i=0; $i<count($errors); $i++)
  {
    print($errors[$i] . PHP_EOL);
  }
  exit(1);
}
if ($namespace == 'db:install') {
  global $user;
  $user = Array('status' => 'webmaster');
  $language = $options['language'];
  $languages = get_all_languages();
  validate_language($language, $languages);
  $errors = [];
  initialize_db($languages, $language, $prefixeTable, $errors);
  if ($errors) {
    for ($i=0; $i<count($errors); $i++)
    {
      print($errors[$i] . PHP_EOL);
    }
    exit(1);
  }
//  mark_all_upgrades_as_done();
}
else if ($namespace == 'user:create')
{
  $password = random_pass();
  global $user;
  $user = Array('id' => 0);
  $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
  session_start();
  $id = register_user($options['login'], $password, $options['mail_address'], false);
  if(array_key_exists('oidc', $options) && !$options['oidc'])
  {
    single_insert(OIDC_TABLE, [
      'sub' => $options['mail_address'],
      'user_id' => $id,
    ]);
  }
}
else if ($namespace == 'user:admin:create')
{
  $language = $options['language'];
  $languages = get_all_languages();
  validate_language($language, $languages);
  add_admin($options['login'], $options['admin_pass'], $options['mail_address'], $options['language']);
}
else if ($namespace == 'config:show')
{
  load_conf_from_db();
  $config = safe_unserialize($conf);
  var_dump($config);
}
else if ($namespace == 'config:modify')
{
  $value = cast_value($options['type'], $options['value']);
  load_conf_from_db();
  conf_update_param($options['conf_name'], $value);
}
else if ($namespace == 'plugin:activate')
{
  global $user, $template;
  $user = Array('status' => 'webmaster', 'id' => 0);
  $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
  session_start();
  $template = new Template(PHPWG_ROOT_PATH.'admin/themes', 'clear');
  $conf['secret_key'] = 'secret';
  $params =  array(
        'action'    => 'activate',
        'plugin'    => $options['plugin_name'],
        'pwg_token' => get_pwg_token(),
  );
  $errors = ws_plugins_performAction($params, null);
  if (! $errors) {
    var_dump($errors);
    exit(1);
  }
}
else if ($namespace == 'plugin:deactivate')
{
  global $user, $template;
  $user = Array('status' => 'webmaster');
  $template = new Template(PHPWG_ROOT_PATH.'admin/themes', 'clear');
  $conf['secret_key'] = 'secret';
  $params =  array(
        'action'    => 'deactivate',
        'plugin'    => $options['plugin_name'],
        'pwg_token' => get_pwg_token(),
  );
  $errors = ws_plugins_performAction($params, null);
  if (! $errors) {
    var_dump($errors);
    exit(1);
  }
}
else if ($namespace == 'config:show:array')
{
  load_conf_from_db();
  $config = safe_unserialize($conf[$options['conf_name']]);
  var_dump($config);
}
else if ($namespace == 'config:modify:array')
{
  load_conf_from_db();
  $ori_config = safe_unserialize($conf[$options['conf_name']]);
  $new_config = serialize(custom_array_modify($ori_config, $options));
  conf_update_param($options['conf_name'], $new_config);
}
else if ($namespace == 'config:show:json')
{
  load_conf_from_db();
  $config = json_decode($conf[$options['conf_name']], true);
  var_dump($config);
}
else if ($namespace == 'config:modify:json')
{
  load_conf_from_db();
  if(array_key_exists($options['conf_name'], $conf))
  {
    $ori_config = json_decode($conf[$options['conf_name']], true);
  }
  else
  {
    $ori_config = Array();
  }
  $new_config = json_encode(custom_array_modify($ori_config, $options));
  conf_update_param($options['conf_name'], $new_config);
}
else if ($namespace == 'theme:activate')
{
  global $page, $template;
  $template = new Template(PHPWG_ROOT_PATH.'admin/themes', 'clear');
  $conf['mobile_theme'] = '';
  $page = Array('page' => $options['theme_name']);
  include(PHPWG_ROOT_PATH.'admin/themes_installed.php');
  $themes = new themes();
  $errors = $themes->perform_action('activate', $options['theme_name']);
  if (!empty($errors)) {
    var_dump($errors);
    exit(1);
  }
}
else if ($namespace == 'community:permission:add')
{
  include(PHPWG_ROOT_PATH . 'plugins/community/main.inc.php');
  $insert = array(
    'type' => $options['type'],
    'group_id' => null,
    'user_id' => null,
    'category_id' => null,
    'user_album' => array_key_exists('user_album', $options) ? 'true' : 'false',
    '`recursive`' => array_key_exists('recursive', $options) ? 'true' : 'false',
    'create_subcategories' => array_key_exists('create_subcategories', $options) ? 'true' : 'false',
    'moderated' => array_key_exists('moderated', $options) ? 'true' : 'false',
    'nb_photos' => -1,
    'storage' => -1,
    );
  mass_inserts(
    COMMUNITY_PERMISSIONS_TABLE,
    array_keys($insert),
    array($insert)
    );
}

?>
