<?php
session_start();
require_once __DIR__ . '/../db_config.php';
$pdo = getDB();
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
$confirm_password = $_POST['confirm_password'] ?? '';
if ($username === '' || $email === '' || $password === '') {
$message = '<div class="error">All fields are required!</div>';
} elseif ($password !== $confirm_password) {
$message = '<div class="error">Passwords do not match!</div>';
} else {
try {
// Uniqueness check
$check = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ? LIMIT 1");
$check->execute([$username, $email]);
if ($check->fetch()) {
$message = '<div class="error">Username or email already exists!</div>';
} else {
$pdo->beginTransaction();
// 1) Create DB user -> keep plan_type='free' to match your current schema
$insertUser = $pdo->prepare("
INSERT INTO users (username, email, password_hash, plan_type, status, created_date)
VALUES (?, ?, ?, 'free', 'active', NOW())
");
// NOTE: plain password only for testing
$insertUser->execute([$username, $email, $password]);
$userId = $pdo->lastInsertId();
// 2) Provision SFTP user + directories (Plan A at the infra level)
$systemUser = preg_replace('/[^a-z0-9_-]/i', '', strtolower($username));
$primaryGroup = "sftpusers"; // base group
$planGroup = "plana"; // supplementary group for plan A
$quotaMb = 500; // record only; enforcement handled server-side
$plan = 'a';
$basePath = "/var/www/subdomains";
$userDir = "$basePath/$systemUser";
$filesDir = "$userDir/files";
$domain = $systemUser . ".devbrewing.com";
// Directories
$mkdirOut = shell_exec("sudo mkdir -p " . escapeshellarg($filesDir) . " 2>&1");
// Create Linux user if missing
$userExists = trim(shell_exec("id -u " . escapeshellarg($systemUser) . " 2>/dev/null")) !== '';
if (!$userExists) {
$useraddCmd = "sudo useradd -d " . escapeshellarg($userDir) .
" -g " . escapeshellarg($primaryGroup) .
" -G " . escapeshellarg($planGroup) .
" -s /usr/sbin/nologin " . escapeshellarg($systemUser);
$useraddOut = shell_exec($useraddCmd . " 2>&1");
} else {
$useraddOut = "user already exists";
}
// Set password (must meet PAM policy)
$chpasswdCmd = "echo " . escapeshellarg($systemUser . ':' . $password) . " | sudo chpasswd";
$chpasswdOut = shell_exec($chpasswdCmd . " 2>&1");
// Chroot-friendly perms
$permOut = shell_exec("sudo chown root:root " . escapeshellarg($userDir) . " 2>&1");
$permOut .= shell_exec("sudo chmod 755 " . escapeshellarg($userDir) . " 2>&1");
$permOut .= shell_exec("sudo chown -R " . escapeshellarg($systemUser . ':' . $primaryGroup) . ' ' . escapeshellarg($filesDir) . " 2>&1");
$permOut .= shell_exec("sudo chmod 755 " . escapeshellarg($filesDir) . " 2>&1");
// Optional starter file
$template = "$basePath/_template/index.html";
if (is_file($template)) {
shell_exec("sudo cp " . escapeshellarg($template) . ' ' . escapeshellarg($userDir . '/index.html') . " 2>&1");
}
// 3) Record site (this is where we mark plan 'a')
$insertSite = $pdo->prepare("
INSERT INTO sites (user_id, site_name, domain, plan, root_dir, system_user, group_name, quota_mb)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
");
$insertSite->execute([
$userId,
$systemUser,
$domain,
$plan, // 'a'
$userDir,
$systemUser,
$planGroup, // plana
$quotaMb
]);
$pdo->commit();
// Debug log
$log = "=== Signup " . date('Y-m-d H:i:s') . " ===\n";
$log .= "User: $systemUser ($username)\n";
$log .= "Dir: $userDir\n";
$log .= "mkdir: $mkdirOut\n";
$log .= "useradd: $useraddOut\n";
$log .= "chpasswd: $chpasswdOut\n";
$log .= "perms: $permOut\n\n";
file_put_contents('/tmp/sftp-signup.log', $log, FILE_APPEND);
// Success
$message = '<div class="success">
✅ Account created successfully!<br>
🌐 <b>Subdomain:</b> https://' . htmlspecialchars($domain) . '<br>
🔐 <b>SFTP Login:</b> ' . htmlspecialchars($systemUser) . '<br>
💾 <b>Plan:</b> A (500 MB)<br>
📁 <b>Root Folder:</b> ' . htmlspecialchars($userDir) . '<br>
<a href="login.php">Login here</a>
</div>';
}
} catch (Throwable $e) {
if ($pdo->inTransaction()) { $pdo->rollBack(); }
$message = '<div class="error">Error creating account: ' . htmlspecialchars($e->getMessage()) . '</div>';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Sign Up - DevBrewing</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body { font-family: Arial; margin: 0; background: linear-gradient(135deg,#667eea 0%,#764ba2 100%);
min-height: 100vh; display:flex; align-items:center; justify-content:center; padding:1rem;}
.container { background: white; padding: 2rem; border-radius: 10px;
box-shadow: 0 10px 25px rgba(0,0,0,0.1); width:100%; max-width:400px;}
h1 { text-align: center; margin-bottom: 1.5rem; }
.form-group { margin-bottom: 1rem; }
label { display:block; margin-bottom:.5rem; font-weight:bold; }
input { width:100%; padding:.75rem; border:1px solid #ddd; border-radius:5px; font-size:1rem;}
.btn { width:100%; padding:.75rem; background:#667eea; color:#fff; border:none;
border-radius:5px; cursor:pointer;}
.btn:hover { background:#5a67d8; }
.error, .success { padding:.75rem; border-radius:5px; margin-bottom:1rem; }
.error { background:#fee; color:#c33; }
.success { background:#efe; color:#393; }
.links { text-align:center; margin-top:1rem; }
</style>
</head>
<body>
<div class="container">
<h1>🎮 Join the Platform</h1>
<?php echo $message; ?>
<form method="POST">
<div class="form-group">
<label>Username:</label>
<input type="text" name="username" required>
</div>
<div class="form-group">
<label>Email:</label>
<input type="email" name="email" required>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" name="password" required>
</div>
<div class="form-group">
<label>Confirm Password:</label>
<input type="password" name="confirm_password" required>
</div>
<button type="submit" class="btn">Create Account</button>
</form>
<div class="links">
<a href="login.php">Login</a> | <a href="<?php echo SITE_URL ?? '/'; ?>">Back to Home</a>
</div>
</div>
</body>
</html>