<?php

// controller.php
// ``````````````

// Set up environment

require __DIR__.'/config.php';
require __DIR__.'/common.php';
require __DIR__.'/application.php';

error_reporting(E_ALL);
ini_set('display_errors', 'Off');

/**
 * 
 * @param string $ROUTE
 */
function routeRequest($ROUTE) {
	$matches = [];
	$arc = new ArchiveState();
		
	if (hasGet('y') || hasGet('q') || hasGet('h')) {
		redirectLegacyURL();
	
	} elseif ($ROUTE == '/') {
		$HUBS = getHubs();
		redirect('/0/'.$HUBS[0][4].'/'.$HUBS[0][5]);
		
	} elseif (preg_match('~^/(\d+)/(\d+)/(\d+)$~', $ROUTE, $matches)) {
		$arc->setHub( $matches[1] );
		$arc->year  = $matches[2];
		$arc->month = $matches[3];
		$arc->renderView();
		
	} elseif (preg_match('~^/(\d+)/(\d+)/(\d+)/(\d+)$~', $ROUTE, $matches)) {
		$arc->setHub( $matches[1] );
		$arc->page  = $matches[4];
		$arc->year  = $matches[2];
		$arc->month = $matches[3];
		$arc->renderView();

	} elseif (preg_match('~^/(\d+)/search/(.*)$~', $ROUTE, $matches)) {
		$arc->setHub( $matches[1] );
		$arc->query = rawurldecode($matches[2]);
		$arc->regex = false;
		$arc->renderSearch();

	} elseif (preg_match('~^/(\d+)/rx/(.*)~', $ROUTE, $matches)) {
		$arc->setHub( $matches[1] );
		$arc->query = rawurldecode($matches[2]);
		$arc->regex = true;
		$arc->renderSearch();

	} elseif (preg_match('~^/download$~', $ROUTE, $matches)) {
		streamArchive();
		die();
		
	} else {
		$arc->renderError('Unknown route');
	}
	
}

/**
 * 
 */
function redirectLegacyURL() {
	
	$hubid = hasGet('h') ? intval($_GET['h']) : 0;
	if (hasGet('q')) {
		if (hasGet('rx')) {
			redirect('/'.$hubid.'/rx/'.rawurlencode($_GET['q']));
		} else {
			redirect('/'.$hubid.'/search/'.rawurlencode($_GET['q']));
		}
	} else {
		if (hasGet('y') && hasGet('m')) {
			$year  = hasGet('y') ? intval($_GET['y']) : date('Y');
			$month = hasGet('m') ? intval($_GET['m']) : date('m');
			if (hasGet('p')) {
				$page = intval($_GET['p']);
				redirect('/'.$hubid.'/'.$year.'/'.$month.'/'.$page);
			} else {
				redirect('/'.$hubid.'/'.$year.'/'.$month);
			}
		} else {
			$HUBS = getHubs();
			if (array_key_exists($_GET['h'], $HUBS)) {
				redirect('/'.$_GET['h'].'/'.$HUBS[$_GET['h']][4].'/'.$HUBS[$_GET['h']][5]);
			} else {
				redirect('/');
			}
		}
	}
}

/**
 *
 */
function streamArchive() {	
	$allfiles = [];
	
	foreach(getHubs() as $id => $hubinfo) {
		
		foreach(monthrange($hubinfo[2], $hubinfo[3], $hubinfo[4], $hubinfo[5]) as $ympair) {
			list($y, $m) = $ympair;
			$chatfile = strftime($hubinfo[1], strtotime($y.'-'.$m));
			
			if (file_exists($chatfile)) {
				$allfiles[] = $chatfile;
			}
		}
	}
	
	$flist = tempnam(sys_get_temp_dir(), 'archive');
	
	file_put_contents($flist, implode("\n", $allfiles));
	
	header('Content-Type: application/octet-stream');
	header('Content-Disposition: attachment; filename="chat-archive-'.date('YmdHis').'.tar.gz"');
	
	passthru('/bin/tar cz --transform \'s~.*/([^/]+/)~\\1~gx\' --files-from '.escapeshellarg($flist));
	
	unlink($flist);
	
	die(0);
}
