#!/usr/bin/php
<?php

const N="\n";

use function mysqli_real_escape_string as myesc;

function mexit($msg,$code) {
	echo($msg);
	exit($code);
}

$iniarr=@parse_ini_file(__DIR__.'/../../conf/mustard.ini')
	or mexit('Impossibile aprire il file di configurazione.'.N,1);
$link=mysqli_connect($iniarr['db_host'],$iniarr['db_admin_name'],$iniarr['db_admin_password'],$iniarr['db_name'],$iniarr['db_port'],$iniarr['db_socket'])
	or mexit('Impossibile connettersi al database: '.mysqli_connect_error().' ['.mysqli_connect_errno().']'.N,1);
mysqli_set_charset($link,'utf8mb4');

$res=mysqli_query($link,'SELECT * FROM Languages WHERE Code LIKE "%-%"');
$dashlangs=[];
while ($row=mysqli_fetch_assoc($res)) $dashlangs[]=$row;
print_r($dashlangs);
foreach ($dashlangs as $dashlang) {
	$normcode=str_replace('-','_',$dashlang['Code']);
	$res=mysqli_query($link,'SELECT * FROM Languages WHERE Code=\''.$normcode.'\'');
	$nr=mysqli_num_rows($res);
	if ($nr==1) {
		$row=mysqli_fetch_assoc($res);
		echo('Di «'.$normcode.'» ce n’è una: ');
		print_r($row);
		$res=mysqli_query($link,'SELECT * FROM InstLangs WHERE LangID='.$row['ID']);
		echo('...linkata '.mysqli_num_rows($res).' volte in InstLangs'.N);
		$res=mysqli_query($link,'SELECT * FROM InstOurLangs WHERE OurLangID='.$row['ID']);
		echo('...e '.mysqli_num_rows($res).' volte in InstOurLangs'.N);
		mysqli_query($link,'UPDATE InstLangs SET LangID='.$row['ID'].' WHERE LangID='.$dashlang['ID']);
		mysqli_query($link,'UPDATE InstOurLangs SET OurLangID='.$row['ID'].' WHERE OurLangID='.$dashlang['ID']);
		mysqli_query($link,'DELETE FROM Languages WHERE Code=\''.$dashlang['Code'].'\'');
	} elseif ($nr>1) {
		echo('MANNAGGIA, di «'.$normcode.'» ce ne sono '.$nr.'!'.N);
	} else {
		echo('Di «'.$normcode.'» non ce ne sono.'.N);
		mysqli_query($link,'UPDATE Languages SET Code=\''.$normcode.'\' WHERE Code=\''.$dashlang['Code'].'\'');
	}
	echo(N);
}
mysqli_close($link);

exit(0);

?>
