// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

// This file is auto-generated by gen_target.sh based on target_template.txt
// To modify it, modify target_template.txt and run gen_target.sh instead.

#![cfg_attr(feature = "libfuzzer_fuzz", no_main)]
#![cfg_attr(rustfmt, rustfmt_skip)]

#[cfg(not(fuzzing))]
compile_error!("Fuzz targets need cfg=fuzzing");

#[cfg(HASHES_FLAG)]
compile_error!("Fuzz target does not support cfg(HASHES_FLAG)");

#[cfg(not(secp256k1_fuzz))]
compile_error!("Fuzz targets need cfg=secp256k1_fuzz");

extern crate lightning_fuzz;
use lightning_fuzz::TARGET_MOD::*;
use lightning_fuzz::utils::test_logger;

#[cfg(feature = "afl")]
#[macro_use] extern crate afl;
#[cfg(feature = "afl")]
fn main() {
	fuzz!(|data| {
		TARGET_NAME_test(&data, test_logger::DevNull {});
	});
}

#[cfg(feature = "honggfuzz")]
#[macro_use] extern crate honggfuzz;
#[cfg(feature = "honggfuzz")]
fn main() {
	loop {
		fuzz!(|data| {
			TARGET_NAME_test(&data, test_logger::DevNull {});
		});
	}
}

#[cfg(feature = "libfuzzer_fuzz")]
#[macro_use] extern crate libfuzzer_sys;
#[cfg(feature = "libfuzzer_fuzz")]
fuzz_target!(|data: &[u8]| {
	TARGET_NAME_test(data, test_logger::DevNull {});
});

#[cfg(feature = "stdin_fuzz")]
fn main() {
	use std::io::Read;

	// On macOS, panic=abort causes the process to send SIGABRT which can leave it
	// stuck in an uninterruptible state due to the ReportCrash daemon. Using
	// process::exit in a panic hook avoids this by terminating cleanly.
	#[cfg(target_os = "macos")]
	std::panic::set_hook(Box::new(|panic_info| {
		use std::io::Write;
		let _ = std::io::stdout().flush();
		eprintln!("{}\n{}", panic_info, std::backtrace::Backtrace::force_capture());
		let _ = std::io::stderr().flush();
		std::process::exit(1);
	}));

	let mut data = Vec::with_capacity(8192);
	std::io::stdin().read_to_end(&mut data).unwrap();
	if std::env::var_os("LDK_FUZZ_SUPPRESS_LOGS").is_some() {
		TARGET_NAME_test(&data, test_logger::DevNull {});
	} else {
		TARGET_NAME_test(&data, test_logger::Stdout {});
	}
}

#[test]
fn run_test_cases() {
	use std::fs;
	use std::io::Read;
	use lightning_fuzz::utils::test_logger::StringBuffer;

	use std::sync::{atomic, Arc};
	{
		let data: Vec<u8> = vec![0];
		TARGET_NAME_test(&data, test_logger::DevNull {});
	}
	let mut threads = Vec::new();
	let threads_running = Arc::new(atomic::AtomicUsize::new(0));
	if let Ok(tests) = fs::read_dir("../test_cases/TARGET_NAME") {
		for test in tests {
			let mut data: Vec<u8> = Vec::new();
			let path = test.unwrap().path();
			fs::File::open(&path).unwrap().read_to_end(&mut data).unwrap();
			threads_running.fetch_add(1, atomic::Ordering::AcqRel);

			let thread_count_ref = Arc::clone(&threads_running);
			let main_thread_ref = std::thread::current();
			threads.push((path.file_name().unwrap().to_str().unwrap().to_string(),
				std::thread::spawn(move || {
					let string_logger = StringBuffer::new();

					let panic_logger = string_logger.clone();
					let res = if ::std::panic::catch_unwind(move || {
						TARGET_NAME_test(&data, panic_logger);
					}).is_err() {
						Some(string_logger.into_string())
					} else { None };
					thread_count_ref.fetch_sub(1, atomic::Ordering::AcqRel);
					main_thread_ref.unpark();
					res
				})
			));
			while threads_running.load(atomic::Ordering::Acquire) > 32 {
				std::thread::park();
			}
		}
	}
	let mut failed_outputs = Vec::new();
	for (test, thread) in threads.drain(..) {
		if let Some(output) = thread.join().unwrap() {
			println!("\nOutput of {}:\n{}\n", test, output);
			failed_outputs.push(test);
		}
	}
	if !failed_outputs.is_empty() {
		println!("Test cases which failed: ");
		for case in failed_outputs {
			println!("{}", case);
		}
		panic!();
	}
}
