<?php
// Base-name
$name = 'foobar';

// Init Magento
require_once 'app/Mage.php';
Mage::app();
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

// Create the root catalog
$category = Mage::getModel('catalog/category');
$category->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID);
$category->setData('name', ucfirst($name).' Catalog');
$category->setData('url_key', $name.'-catalog');
$category->setData('display_mode', 'PRODUCTS');
$category->setData('level', 1);
$category->setData('is_active', 1);
$category->setData('include_in_menu', 1);
$category->setData('is_anchor', 0);
$category->setData('custom_use_parent_settings', 0);
$category->setData('custom_apply_to_products', 0);
$category->setData('attribute_set_id', $category->getDefaultAttributeSetId());
$category->save();
$category->setParentId(1);
$category->setPath('1/'.$category->getId());
$category->save();
$categoryId = $category->getId();

// Load the website
$website = Mage::getModel('core/website')->load($name, 'code');
if($website->getId() > 0) {
    echo "Website already exists\n";
    echo "Updating store-group\n";
    $group = Mage::getModel('core/store_group')->load($websiteId, 'website_id');
    $group->setData('root_category_id', $category->getId());
    $group->save();
    exit;
}

// Create the website
echo "Creating new website\n";
$website->setData('name', ucfirst($name).' Website');
$website->setData('code', $name);
$website->setData('sort_order', 1);
$website->setData('is_default', 0);
$website->save();
$websiteId = $website->getWebsiteId();

// Create the group
echo "Creating new store-group\n";
$group = Mage::getModel('core/store_group')->load($websiteId, 'website_id');
$group->setData('website_id', $websiteId);
$group->setData('name', ucfirst($name).' Store');
$group->setData('root_category_id', $category->getId());
$group->save();
$groupId = $group->getGroupId();

// Create the store
echo "Creating new store\n";
$store = Mage::getModel('core/store_store');
$store->setData('website_id', $websiteId);
$store->setData('group_id', $groupId);
$store->setData('name', ucfirst($name).' Store');
$store->setData('code', $name);
$store->setData('is_active', 1);
$store->save();
$storeId = $store->getStoreId();

// Update the website
echo "Updating website\n";
$website->setData('default_group_id', $groupId);
$website->save();

// Update the group
echo "Updating store-group\n";
$group->setData('default_store_id', $storeId);
$group->save();