#!/usr/bin/env php
<?php
/**
*
* Usage:
*   vendor/bin/create-migration create_user_table
*   → creates a file migrations/mYYMMDD_HHMMSS_create_user_table.php
*/

$migrationsPath = getcwd() . '/migrations';

if ($argc < 2) {
    fwrite(STDERR, "Usage: php {$argv[0]} MigrationDescription\n");
    exit(1);
}

$rawName = $argv[1];
if (!preg_match('/^[A-Za-z0-9_]+$/', $rawName)) {
    fwrite(STDERR, "Invalid name [A-Za-z0-9_].\n");
    exit(1);
}

$timestamp = date('ymd_His');
$className = "m{$timestamp}_{$rawName}";
$fileName  = "{$className}.php";
$filePath  = "{$migrationsPath}/{$fileName}";

if (!is_dir($migrationsPath)) {
    mkdir($migrationsPath, 0755, true);
}

if (file_exists($filePath)) {
    fwrite(STDERR, "File already exists: {$filePath}\n");
    exit(1);
}

$stub = <<<PHP
<?php

class {$className} extends CDbMigration
{
    public function up()
    {

    }

    public function down()
    {
        return false;
    }
}
PHP;

if (false === file_put_contents($filePath, $stub)) {
    fwrite(STDERR, "could not create file.\n");
    exit(1);
}

fwrite(STDOUT, "Migration created successfully: {$filePath}\n");
exit(0);
