Skip to content

Commit

Permalink
Merge branch 'main' into mbround18-patch-1
Browse files Browse the repository at this point in the history
  • Loading branch information
mbround18 authored Feb 5, 2021
2 parents eaff91c + bfcb510 commit 983d7dc
Show file tree
Hide file tree
Showing 12 changed files with 258 additions and 107 deletions.
75 changes: 75 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
pad = "0.1"
log = "0.4.14"
clap = { version = "3.0.0-beta.2", features = ["yaml"] }
which = "4.0.2"
dialoguer = "0.7.1"
tinytemplate = "1.1"
serde = { version = "1.0", features = ["derive"] }

[profile.dev]
opt-level = 0
Expand Down
3 changes: 2 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ services:
- "2457:2457/udp"
- "2458:2458/udp"
volumes:
- ./tmp/valheim:/home/steam/valheim
- ./tmp/valheim/saves:/home/steam/.config/unity3d/IronGate/Valheim
- ./tmp/valheim/server:/home/steam/valheim
5 changes: 2 additions & 3 deletions scripts/entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,8 @@ cleanup() {
exit
}

trap cleanup INT TERM
trap cleanup EXIT
trap cleanup INT TERM EXIT

while :; do
sleep 1s
sleep 1s
done
15 changes: 15 additions & 0 deletions src/cli.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@ name: odin
version: "0.1.0"
author: mbround18
about: Installs and Runs Valheim
args:
- debug:
short: d
long: debug
multiple: true
help: Sets the logger to log debug events.
takes_value: false
- dry_run:
short: r
global: true
long: dry-run
about: Will output the commands that it intends to run.

subcommands:
- install:
about: Installs Valheim with steamcmd
Expand Down Expand Up @@ -31,10 +44,12 @@ subcommands:
about: Sets the world of the server, (Can be set with ENV variable WORLD)
takes_value: true
- password:
short: s
long: password
value_name: PASSWORD
about: Sets the password of the server, (Can be set with ENV variable PASSWORD)
takes_value: true

- stop:
about: Stops Valheim
version: "1.0"
Expand Down
3 changes: 3 additions & 0 deletions src/commands/initialize.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// pub fn invoke(args: Option<&ArgMatches>) {
// let option
// }
1 change: 1 addition & 0 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod install;
pub mod start;
pub mod stop;
pub mod initialize;
141 changes: 74 additions & 67 deletions src/commands/start.rs
Original file line number Diff line number Diff line change
@@ -1,85 +1,92 @@
use crate::executable::{create_execution};
use std::process::{Stdio};
use clap::{ArgMatches};
use std::{process};
use crate::utils::{get_working_dir, get_variable};
use std::path::Path;
use crate::utils::{get_variable, server_installed, get_working_dir};
use std::fs::{File};
use std::io::Write;
use log::{info, error};
use tinytemplate::TinyTemplate;
use serde::Serialize;

#[derive(Serialize)]
struct Context {
command: String,
arguments: String
}

fn create_start_server_script(command: String, arguments: String) {
let source = &[
"#!/usr/bin/env bash",
format!("{} {} &", command.as_str(), arguments.as_str()).as_str(),
"disown"
].join("\n");
static TEMPLATE: &'static &str = &r#"
#!/usr/bin/env bash
cd "$(dirname "$0")"
# This script will be overwritten at each start!
match File::create("./start_server_rusty.sh") {
Ok(mut file) => {
match file.write_all(source.as_bytes()) {
Ok(_) => println!("Successfully written script file."),
_ => println!("Failed to write script file.")
};
{command} {arguments} 2>&1 | tee ./output.log &
disown
match create_execution("chmod").args(&["+x", "./start_server_rusty.sh"]).output() {
Ok(_) =>println!("Success changing permission"),
_ => println!("Unable to change permissions")
};
}
_ => println!("Failed to write script file.")
};
}
"#;

pub fn invoke(args: Option<&ArgMatches>) {
let paths = &[get_working_dir(), "valheim_server.x86_64".to_string()];
let script_path = &paths.join("/");
let script_file = Path::new(script_path);
if script_file.exists() {
let mut command = create_execution("bash");
let mut command_arguments: Vec<String> = Vec::new();
fn parse_to_script(context: Context) -> String{
let mut tt = TinyTemplate::new();
tt.add_template(
"hello", &TEMPLATE).unwrap();
tt.render("hello", &context).unwrap().replace("&quot;", "\"")
}

if let Some(port) = get_variable("PORT", args, "2456".to_string()) {
println!("Found Port Argument: {}", port);
command_arguments.push(format!("-port {}", port));
}
if let Some(name) = get_variable("NAME", args, "Valheim Docker".to_string()) {
println!("Adding Name Argument: {}", name);
command_arguments.push(format!("-name \"{}\"", name));
}
if let Some(world) = get_variable("WORLD", args, "Dedicated".to_string()) {
println!("Adding World Argument: {}", world);
command_arguments.push(format!("-world \"{}\"", world));
}
if let Some(password) = get_variable("PASSWORD", args, "".to_string()) {
if password.len() > 0 {
println!("Adding Password Argument");
command_arguments.push(format!("-password \"{}\"", password));
fn create_start_server_script(command: String, arguments: String, dry_run: bool) {
let context = Context {
command,
arguments
};
let source = parse_to_script(context);
if dry_run {
info!("This would have written a file to ./start_server_rusty.sh with content: \n {}", source);
} else {
match File::create("./start_server_rusty.sh") {
Ok(mut file) => {
match file.write_all(source.as_bytes()) {
Ok(_) => println!("Successfully written script file."),
_ => println!("Failed to write script file.")
};
match create_execution("chmod").args(&["+x", "./start_server_rusty.sh"]).output() {
Ok(_) => info!("Success changing permission"),
_ => error!("Unable to change permissions")
};
}
}

create_start_server_script(script_path.to_string(), command_arguments.join(" "));

let updated_command = command
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.arg("-c")
.arg("./start_server_rusty.sh")
.env("LD_LIBRARY_PATH", "${PWD}/linux64:${LD_LIBRARY_PATH}");
_ => error!("Failed to write script file.")
};
}
}

fn parse_arg(args: &ArgMatches, name: &str, default: &str) -> String {
format!("-{} \"{}\"", name, get_variable(args, name,default.to_string()))
}

match updated_command.output() {
Ok(output) => print!("Exit with code {}", output.status),
_ => {
print!("An error has occurred!")
pub fn invoke(args: &ArgMatches) {
let mut command = create_execution("bash");
let command_args: &str = &[
parse_arg(args, "port", "2456"),
parse_arg(args, "name", "Valheim Docker"),
parse_arg(args, "world", "Dedicated"),
parse_arg(args, "password", "12345"),
].join(" ");
let dry_run: bool = args.is_present("dry_run");
let server_executable = &[get_working_dir(), "valheim_server.x86_64".to_string()].join("/");
create_start_server_script(server_executable.to_string(), command_args.to_string(), dry_run);
if !dry_run {
if server_installed() {
let updated_command = command
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.arg("-c")
.arg("./start_server_rusty.sh")
.env("LD_LIBRARY_PATH", "${PWD}/linux64:${LD_LIBRARY_PATH}");
match updated_command.output() {
Ok(output) => print!("Exit with code {}", output.status),
_ => {
error!("An error has occurred!")
}
}
} else {
error!("Could not find server executable! Please install the server!")
}
// updated_command.exec();
// let result = execute_mut(updated_command);
// handle_exit_status(result, "Server Started Successfully!".to_string());

} else {
println!("Cannot start server! valheim_server.x86_64 not found in current directory!");
process::exit(1)
}
}
37 changes: 25 additions & 12 deletions src/commands/stop.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
use crate::utils::get_working_dir;
use crate::executable::{create_execution, execute_mut, handle_exit_status};
use std::process::Stdio;
use crate::utils::{get_working_dir, server_installed};
use log::{info, error};
use clap::ArgMatches;
use std::fs::{File, remove_file};
use std::io::Write;
use std::thread::sleep;
use std::time::Duration;

pub fn invoke() {
pub fn invoke(args: &ArgMatches) {
let paths = &[get_working_dir(), "server_exit.drp".to_string()];
let script_path = &paths.join("/");
let mut command = create_execution(format!("echo 1 > {}", script_path).as_str());
let updated_command = command
.stdout(Stdio::inherit())
.stderr(Stdio::inherit());

let result = execute_mut(updated_command);
handle_exit_status(result, "Server Stopped Successfully!".to_string())

info!("Stopping server {}", get_working_dir());
let command_arguments = format!("> {}", script_path);
if args.is_present("dry_run") {
info!("This command would have run: ");
info!("echo {}", command_arguments)
} else {
if !server_installed() {
error!("Failed to find server executable!");
return;
}
let mut file = File::create(script_path).unwrap();
file.write_all(b"1").unwrap();
info!("Stop file created, waiting for server to stop!");
sleep(Duration::from_secs(5));
remove_file(script_path).unwrap();
info!("Server has been halted!");
}
}
Loading

0 comments on commit 983d7dc

Please sign in to comment.