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
use super::RapidCommand;
use crate::cli::{current_directory, logo, Config};
use crate::rapid_config::config::{is_rapid, find_rapid_config, AppType};
use clap::{arg, value_parser, ArgAction, ArgMatches, Command};
use std::str::FromStr;
use std::{path::PathBuf, process::Command as StdCommand};
use spinach::Spinach;

pub struct Run {}

impl RapidCommand for Run {
	fn cmd() -> clap::Command {
		Command::new("run").about("A command for running various rapid applications").arg(
			arg!(
				-server --server "Runs a rapid server application"
			)
			.required(false)
			.action(ArgAction::SetTrue)
			.value_parser(value_parser!(PathBuf)))
			.arg(arg!(
				-app --app "Runs a rapid fullstack application"
			)
			.required(false)
			.action(ArgAction::SetTrue)
			.value_parser(value_parser!(PathBuf)))
	}

	fn execute(_: &Config, args: &ArgMatches) -> Result<(), crate::cli::CliError<'static>> {
		println!("{}", logo());
		parse_run_args(args).unwrap();
		// The above code never errors out...
		Ok(())
	}
}


fn parse_run_args(args: &ArgMatches) -> Result<(), ()> {
	// // We want to early exit before do anything at all if we are not inside of a rapid application
	if !is_rapid() {
		eprintln!("Could not find a valid config file in the current working directory. Please make sure you are in a official rapid project before running this command.");
		// Exit 64 is a standard error code..
		std::process::exit(64);
	}

	// As we add support for more apps this array can grow
	const RUN_ARGS: [&str; 2] = ["server", "app"];

	for arg in RUN_ARGS {
		match args.get_one::<PathBuf>(arg) {
			Some(val) => {
				if val == &PathBuf::from("true") {
					match arg {
						"server" => {
							handle_run_server();
							return Ok(());
						}
						"app" => {
							println!("Coming soon!");
							return Ok(());
						}
						// Eventually, "rapid run" should default to running in application mode, not server mode
						_ => {
							println!("{} {}", "No application found for the type: ", arg);
							return Ok(());
						}
					}
				}
			}
			None => {
				println!("No rapid 'run' applications found. Try one of the following: ['server']");
				return Ok(());
			},
		}
	}

	// If no valid args were inputted then we want to fallback to the rapid config file
	let rapid_config = find_rapid_config();
	let application_type = AppType::from_str(&rapid_config.app_type).expect("Error: invalid rapid application type!");
	match application_type {
		AppType::App => {
			// Currently app does nothing (we are yet to implement this)
			println!("Coming soon...");
		},
		AppType::Server => {
			handle_run_server();
			return Ok(());
		}
		_ => {
			eprintln!("Error: invalid rapid application type!")
		}
	}

	Ok(())
}


fn handle_run_server() {

	// Before running this script we need to check if the user has cargo-watch and systemfd on their machine
	// If they do, we want to continue -- however, if they dont, we need to trigger an isntall of the binaries
	let install_list = StdCommand::new("sh")
		.arg("-c")
		.arg("cargo install --list")
		.output()
		.expect("Could not complete pre-run checks.");

	// Check if the user had cargo-watch and systemfd
	if !std::str::from_utf8(&install_list.stdout).unwrap().contains("cargo-watch")
		|| !std::str::from_utf8(&install_list.stdout).unwrap().contains("systemfd") {
		let s = Spinach::new("Installing build scripts...");
		// To be safe, lets install both cargo-watch and systemfd
		StdCommand::new("sh")
			.arg("-c")
			.arg("cargo install cargo-watch")
			.output()
			.expect("Could not install rapid dev server binaries. Please try again.");

		StdCommand::new("sh")
		.arg("-c")
		.arg("cargo install systemfd")
		.output()
		.expect("Could not install rapid dev server binaries. Please try again.");

		s.succeed("Rapid build scripts installed!");
	}

	StdCommand::new("sh")
	.current_dir(current_directory())
	.arg("-c")
	.arg("systemfd --no-pid -s http::8080 -- cargo watch -x run")
	.spawn()
	.unwrap()
	.wait_with_output()
	.expect("command failed to start");

	// We need to register a handler here to quite the running process
	ctrlc::set_handler(move || {
		std::process::exit(0);
	})
	.expect("Error: Could not stop process");
}