#!/usr/bin/env php
<?php declare(strict_types=1);

function ask( string $question, string $default = '' ): string {
	$answer = readline( $question . ( $default ? " ($default)" : null ) . ': ' );

	if ( ! $answer ) {
		return $default;
	}

	return $answer;
}

function confirm( string $question, bool $default = false ): bool {
	$answer = ask( $question . ' (' . ( $default ? 'Y/n' : 'y/N' ) . ')' );

	if ( ! $answer ) {
		return $default;
	}

	return strtolower( $answer ) === 'y';
}

function replace_in_file( string $file, array $replacements ): void {
	$contents = file_get_contents( $file );

	file_put_contents(
			$file,
			str_replace(
					array_keys( $replacements ),
					array_values( $replacements ),
					$contents
			)
	);
}

function writeln( string $line ): void {
	echo $line . PHP_EOL;
}

function run( string $command ): string {
	return trim( shell_exec( $command ) ?: '' );
}

parse_str( implode( '&', array_slice( $argv, 1 ) ), $result );

$domain = $result['domain'] ?? ask( 'Text Domain Name', 'my-text-domain' );

if ( empty( $domain ) ) {
	writeln( 'Translation domain could not be empty' );
	exit( 0 );
}

if ( ! confirm( 'Modify files?', true ) ) {
	exit( 1 );
}

$files = explode( PHP_EOL, run( 'grep -E -r -l -i "%TEXTDOMAIN%" "' . dirname( __FILE__, 2 ) . '/src"' ) );
$files = array_filter( $files );

foreach ( $files as $file ) {
	replace_in_file( $file, [
			'%TEXTDOMAIN%' => $domain
	] );
}
