<?php

use Vn\Lib;
use Vn\Lib\UserException;

/**
 * Uploads a access module.
 */
class AccessVersion extends Vn\Web\JsonRequest
{
	const PARAMS = [
		 'appName'
		,'newVersion'
	];

	function run ($db)
	{		
		// Checks for file errors.

		$moduleFile = $_FILES['moduleFile'];
		
		if (empty ($moduleFile['name']))
			throw new UserException (s('File not choosed'));

		if ($moduleFile['error'] != 0)
		{
			switch ($_FILES['image']['error'])
			{
		        case UPLOAD_ERR_INI_SIZE:
		            $message = 'ErrIniSize';
		            break;
		        case UPLOAD_ERR_FORM_SIZE:
		            $message = 'ErrFormSize';
		            break;
		        case UPLOAD_ERR_PARTIAL:
		            $message = 'ErrPartial';
		            break;
		        case UPLOAD_ERR_NO_FILE:
		            $message = 'ErrNoFile';
		            break;
		        case UPLOAD_ERR_NO_TMP_DIR:
		            $message = 'ErrNoTmpDir';
		            break;
		        case UPLOAD_ERR_CANT_WRITE:
		            $message = 'ErrCantWrite';
		            break;
		        case UPLOAD_ERR_EXTENSION:
		            $message = 'ErrExtension';
		            break;
		        default:
		            $message = 'ErrDefault';
		            break;
		    }

			throw new Lib\Exception (s($message));
		}

		// Defining parameters

		$appName = $_REQUEST['appName'];
		$newVersion = $_REQUEST['newVersion'];

		$uploadDir = '/mnt/cluster/vn-access';
		$uploadFile = "$uploadDir/$appName.7z";
		$archiveDir = "$uploadDir/.archive/$appName";
		$archiveFile = "$archiveDir/$newVersion.7z";

		// Updates the application

		copy ($moduleFile['tmp_name'], $archiveFile);
		rename ($moduleFile['tmp_name'], $uploadFile);

		return TRUE;
	}
}

