<?php

if (!defined('IN_WACKO'))
{
	exit;
}

const ACTIONS			= ['lang', 'version-check', 'config-site', 'config-database', 'install-database', 'write-config'];
const APP_NAME			= 'wackowiki';
const MIN_VERSION		= '6.1.29';
const SET_MENU			= 1;
const SET_MENU_ADMIN	= 2;
const SET_MENU_ONLY		= 3;
const SETUP_LOCK		= 'config/lock_setup';
const SQLITE_DB_FILE	= '.ht.sqlite';

class Installer
{
	static function run(&$db)
	{
		global $config, $base_path;
		$config		= $db->steal_config();
		$base_path	= $db->get_base_url();
		$logged_in	= true;

		// check for missing setup folder
		if (!file_exists('setup/header.php'))
		{
			header('HTTP/1.1 503 Service Unavailable');
			die('WackoWiki fatal error: setup/ folder is missing or empty. Please add the missing setup folder in order to upgrade your WackoWiki installation.');
		}

		require_once 'setup/common.php';

		// Merge new defaults during upgrade
		if (array_key_exists('wacko_version', $config))
		{
			$found_rewrite_extension = ((function_exists('apache_get_modules') && in_array('mod_rewrite', apache_get_modules()))
				|| ((getenv('HTTP_MOD_ENV') === 'on') && (getenv('HTTP_MOD_REWRITE') === 'on')));

			require CONFIG_DEFAULTS;

			// Merge defaults, preserving existing values but adding new ones
			$config = array_merge($wacko_config_defaults, $config);
		}

		$logged_in	= false;

		// check for locking
		if ($lock_file = !empty_file(SETUP_LOCK))
		{
			// read password from lockfile
			$lines		= file(SETUP_LOCK);
			$lock_pw	= trim($lines[0]);

			if (isset($_POST['config']['auth']))
			{
				$auth_token = $_POST['config']['auth'];
			}

			// Check for auth token
			if (!empty($auth_token))
			{
				if (validate_token($auth_token, $lock_pw))
				{
					$logged_in = true;
				}
			}

			// Handle login form submission
			if (!$logged_in && !empty($_POST['setup_auth']))
			{
				$input_pass = $_POST['password'] ?? '';

				if ($lock_pw === $input_pass)
				{
					$config['auth']	= generate_secure_token($lock_pw);
					$logged_in		= true;
				}
				else
				{
					$error = true;
				}

				// reset
				$_REQUEST['installAction'] = '';
			}
		}

		$install_action = trim((string) ($_REQUEST['installAction'] ?? ''));

		// call installer
		if (!$logged_in)
		{
			$install_action = 'login';
		}
		else if (!$install_action || !in_array($install_action, ACTIONS))
		{
			$install_action = 'lang';
		}

		$install_module = 'setup/' . $install_action . '.php';
		require_once 'setup/header.php';


		if (@file_exists($install_module))
		{
			require_once $install_module;
		}
		else
		{
			echo '<p><em>' . $lang['InvalidAction'] . '</em></p>';
		}

		require_once 'setup/footer.php';

		exit;
	}
}
