#!/usr/bin/php
<?php

$host = 'sql.mit.edu';
$env_user = getenv('USER');
$home = '/mit/'.$env_user;

$cnfPath = $home.'/.sql/my.cnf';

function getMyCnfInfo($path) {
if (file_exists($path)) {
	global $env_user;
	$cnfFile = file_get_contents($path);
	if (preg_match('/\[mysql\][^\[]*host *= *([^\r\n]*)/',$cnfFile,$match)) {
		$host = $match[1];
	} elseif (preg_match('/\[client\][^\[]*host *= *([^\r\n]*)/',$cnfFile,$match)) {
		$host = $match[1];
	} else {
		$host = 'sql.mit.edu';
	}
	if (preg_match('/\[mysql\][^\[]*user *= *([^\r\n]*)/',$cnfFile,$match)) {
		$user = $match[1];
	} elseif (preg_match('/\[client\][^\[]*user *= *([^\r\n]*)/',$cnfFile,$match)) {
		$user = $match[1];
	} else {
		$user = $env_user;
	}
	if (preg_match('/\[mysql\][^\[]*password *= *([^\r\n]*)/',$cnfFile,$match)) {
		$password = $match[1];
	} elseif (preg_match('/\[client\][^\[]*password *= *([^\r\n]*)/',$cnfFile,$match)) {
		$password = $match[1];
	} else {
		$password = 'password';
	}
	return array($host,$user,$password);
}
}

$cnfinfo = getMyCnfInfo($cnfPath);
if (is_array($cnfinfo)) {
	list($h,$u,$p) = $cnfinfo;
	echo "$h\t$u\t$p";
	exit;
}

$sql_status = file_get_contents('https://sql.mit.edu/main/do/batch/status?u=' . urlencode($env_user));
switch($sql_status) {
	case 1:
		$myPassword = `/usr/bin/sql-signup`;
        file_put_contents($cnfPath, "[mysql]\nhost=$host\nuser=$env_user\npassword=$myPassword\n");
        $cnfinfo = getMyCnfInfo($cnfPath);
        if (is_array($cnfinfo)) {
            list($h,$u,$p) = $cnfinfo;
    	    echo "$h\t$u\t$p";
        }
		break;
	case 0:
}
