1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/*
 *	VMKS exam generator - A simple program for pseudo-randomly generating different variants of an embedded programming exam
 *	Copyright (C) 2022 - 2023 Vladimir Garistov <vl.garistov@gmail.com>
 *
 *	This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU Affero General Public License as published
 *	by the Free Software Foundation, version 3.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU Affero General Public License for more details.
 *
 *	You should have received a copy of the GNU Affero General Public License
 *	along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

mod question_bank;
mod helpers;

use std::error::Error;
use std::time::SystemTime;
use std::fs;
use std::fs::File;
use std::io::Write;
use std::collections::hash_map::DefaultHasher;
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher};
use std::ffi::OsString;
use std::process::Command;

use clap::ArgMatches;
use rand::prelude::*;
use rand_pcg::Lcg128Xsl64;
use question_bank::QuestionBank;

mod constants
{
	pub const QUESTION_BANK_TAG_NAME_LONG: &str = "question_bank";
	pub const QUESTION_BANK_TAG_NAME: &str = "qb";
	pub const TITLE_ATTRIBUTE_NAME: &str = "title";
	pub const DESCRIPTION_TAG_NAME_LONG: &str = "description";
	pub const DESCRIPTION_TAG_NAME: &str = "d";
	pub const QUESTION_GROUP_TAG_NAME_LONG: &str = "question_group";
	pub const QUESTION_GROUP_TAG_NAME: &str = "qg";
	pub const PICK_ATTRIBUTE_NAME: &str = "pick";
	pub const SHUFFLE_ATTRIBUTE_NAME: &str = "shuffle";
	pub const QUESTION_MC_TAG_NAME_LONG: &str = "question_mc";
	pub const QUESTION_MC_TAG_NAME: &str = "qmc";
	pub const QUESTION_VAR_TAG_NAME_LONG: &str = "question_var";
	pub const QUESTION_VAR_TAG_NAME: &str = "qv";
	pub const TEXT_FIELD_ATTRIBUTE_NAME_LONG: &str = "text_field_height";
	pub const TEXT_FIELD_ATTRIBUTE_NAME: &str = "tfh";
	pub const QUESTION_TEXT_TAG_NAME_LONG: &str = "question_text";
	pub const QUESTION_TEXT_TAG_NAME: &str = "qt";
	pub const ANSWER_MC_TAG_NAME_LONG: &str = "answer_mc";
	pub const ANSWER_MC_TAG_NAME: &str = "amc";
	pub const VAR_TEXT_TAG_NAME_LONG: &str = "var_text";
	pub const VAR_TEXT_TAG_NAME: &str = "vt";
	pub const TEXT_OPTION_TAG_NAME_LONG: &str = "option";
	pub const TEXT_OPTION_TAG_NAME: &str = "o";
	pub const FILE_AUTHOR: &str = "ТУЕС към ТУ-София";
	pub const DEFAULT_TEXT_FIELD_HEIGHT: u16 = 5;
}

#[derive(Debug)]
pub enum VMKSError
{
	InvalidVariants,
	InvalidSeed,
	LaTeXBuildError,
	LaTeXCleanError,
	UnexpectedTag
	{
		expected: String,
		received: String
	},
	UnexpectedAttribute
	{
		expected: String,
		received: String
	},
	UnexpectedText
	{
		expected: String,
		received: String
	},
	PickTooMany,
	InvalidPickValue
	{
		received: String
	},
	InvalidShuffleValue
	{
		received: String
	},
	GenericParseError
}

impl Display for VMKSError
{
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result
	{
		match self
		{
			VMKSError::InvalidVariants => write!(f, "invalid number of variants. Please provide a number greater than 0."),
			VMKSError::InvalidSeed => write!(f, "invalid numeric seed. Use -S for non-numeric seeds."),
			VMKSError::LaTeXBuildError => write!(f, "LaTeX was unable to generate a pdf file for one or more of the exam variants. Check its logs."),
			VMKSError::LaTeXCleanError => write!(f, "Cleaning up LaTeX intermediate files failed."),
			VMKSError::UnexpectedTag{expected, received} =>
			if expected.is_empty()
			{
				write!(f, "unexpected tag. Expected no more tags, got \"{}\".", received)
			}
			else
			{
				write!(f, "unexpected tag. Expected {}, got \"{}\".", expected, received)
			},
			VMKSError::UnexpectedAttribute{expected, received} =>
			if expected.is_empty()
			{
				write!(f, "unexpected attribute. Expected no attributes, got \"{}\".", received)
			}
			else
			{
				write!(f, "unexpected attribute. Expected {}, got \"{}\".", expected, received)
			},
			VMKSError::UnexpectedText{expected, received} =>
				write!(f, "unexpected text. Expected {}, got \"{}\".", expected, received),
			VMKSError::PickTooMany =>
				write!(f, "specified number of questions to pick from a question group is larger than the number of questions in that group."),
			VMKSError::InvalidPickValue{received} =>
				write!(f, "invalid value provided for \"pick\" argument. Expected a non-negative integer, got \"{}\"", received),
			VMKSError::InvalidShuffleValue {received} =>
				write!(f, "invalid value provided for \"randomise\" argument. Expected a \"true\" or \"false\", got \"{}\"", received),
			VMKSError::GenericParseError =>
				write!(f, "unable to parse question bank file.")
		}
	}
}

impl Error for VMKSError {}

pub struct Config
{
	pub seed: u64,
	pub num_variants: u32,
	pub plaintext: bool,
	pub escape: bool,
	pub question_bank_filename: OsString
}

impl Config
{
	pub fn new(arguments: ArgMatches) -> Result<Config, Box<dyn Error>>
	{
		// The following four expressions never panic because default values are provided in main.rs
		let num_variants = *arguments.try_get_one::<u32>("variants")?.unwrap();
		let plaintext = *arguments.try_get_one::<bool>("plaintext")?.unwrap();
		let escape = !*arguments.try_get_one::<bool>("no-escape")?.unwrap();
		let question_bank_filename: OsString = arguments.try_get_one::<OsString>("question-bank")?.unwrap().clone();

		if num_variants == 0
		{
			return Err(Box::new(VMKSError::InvalidVariants));
		}

		let mut seed: u64 = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
		{
			Ok(current_unix_time) => current_unix_time.as_secs(),
			// In case the system clock is set to a point in time before the beginning of the UNIX epoch
			Err(system_time_error) => system_time_error.duration().as_secs()
		};

		if let Some(text_seed) = arguments.try_get_one::<String>("text-seed")?
		{
			let mut hasher = DefaultHasher::new();
			text_seed.hash(&mut hasher);
			seed = hasher.finish();
		}
		else if let Some(num_seed) = arguments.try_get_one::<u64>("num-seed")?
		{
			seed = *num_seed;
		}

		Ok(Config {
			seed,
			num_variants,
			plaintext,
			escape,
			question_bank_filename
		})
	}
}

// Main part of the program
pub fn run(config: Config) -> Result<(), Box<dyn Error>>
{
	let mut rng = Lcg128Xsl64::seed_from_u64(config.seed);
	let question_bank = QuestionBank::from_file(&config.question_bank_filename)?;

	if config.plaintext
	{
		// Generate plaintext variants
		for i in 1..(config.num_variants + 1)
		{
			let mut file = File::create(format!("variant_{}.txt", i))?;
			file.write_all(question_bank.random_variant_txt(&mut rng, config.escape).as_bytes())?;
		}
	}
	else
	{
		let mut files: Vec<String> = Vec::new();
		// Generate LaTeX files
		for i in 1..(config.num_variants + 1)
		{
			let filename = format!("variant_{}.tex", i);
			files.push(filename.clone());
			let mut file = File::create(&filename)?;
			file.write_all(question_bank.random_variant_pdf(&mut rng, config.escape)?.as_bytes())?;
		}

		// Compile LaTeX to PDF
		let mut latex_args: Vec<String> = vec![
			"-silent".to_string(),
			"-interaction=nonstopmode".to_string(),
			"-pdflatex".to_string(),
		];
		latex_args.extend_from_slice(&files);
		let latex_build_ret = Command::new("latexmk").args(latex_args).status()?;
		if latex_build_ret.success()
		{
			let mut latex_args: Vec<String> = vec!["-c".to_string()];
			latex_args.extend_from_slice(&files);
			let latex_clean_ret = Command::new("latexmk").args(latex_args).status()?;
			if !latex_clean_ret.success()
			{
				return Err(Box::new(VMKSError::LaTeXCleanError));
			}
		}
		else
		{
			return Err(Box::new(VMKSError::LaTeXBuildError));
		}

		// Remove LaTeX files
		for file in files.iter()
		{
			fs::remove_file(file)?;
		}
	}

	Ok(())
}