Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setup script #109

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:
rust:
- stable
- beta
- 1.42.0 # minimum required by color-eyre
- 1.46.0
os:
- ubuntu-latest
- macOS-latest
Expand Down
74 changes: 74 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ listenfd = "0.3.3"
libc = "0.2"
once_cell = "1.5.2"
color-eyre = "0.5.1"
dialoguer = "0.7.1"

[[bin]]
name = "echo-server"
Expand Down
15 changes: 10 additions & 5 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
use eyre::Context;
use std::collections::HashMap;
use std::fs::{create_dir, File};
use std::io::prelude::*;
use std::path::PathBuf;
use tokio::fs::{read_dir as async_read_dir, File as AsyncFile};
use tokio::io::AsyncReadExt;
use tokio::stream::StreamExt;

use eyre::Context;
use hyper::header::{HeaderMap, HeaderName, HeaderValue};
use serde::{
de::{self, Unexpected},
Deserialize, Deserializer,
};
use tokio::fs::{read_dir as async_read_dir, File as AsyncFile};
use tokio::io::AsyncReadExt;
use tokio::stream::StreamExt;

use crate::procfile;

Expand Down Expand Up @@ -60,11 +60,15 @@ async fn read_app_config(entry: tokio::io::Result<tokio::fs::DirEntry>) -> color
Ok(app)
}

fn default_proxy_port() -> u16 {
0
}

fn default_dns_port() -> u16 {
6153
}

fn default_domain() -> String {
pub(crate) fn default_domain() -> String {
"test".to_string()
}

Expand All @@ -74,6 +78,7 @@ fn default_idle_timeout_secs() -> u64 {

#[derive(Deserialize, Debug, Clone)]
pub struct ProxyConfig {
#[serde(default = "default_proxy_port")]
pub proxy_port: u16,
#[serde(default = "default_dns_port")]
pub dns_port: u16,
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ mod ipc_listener;
mod ipc_response;
mod output;
mod procfile;
pub mod setup;
mod signals;
mod tmux;

Expand Down
7 changes: 5 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ fn main() -> color_eyre::Result<()> {
.arg(
Arg::with_name("config")
.value_name("CONFIG_FILE")
.help("App config file")
.default_value("apps.toml"),
.help("App config file"),
),
)
.subcommand(
Expand Down Expand Up @@ -39,6 +38,7 @@ fn main() -> color_eyre::Result<()> {
.help("Name of app to stop (defaults to app for current directory)"),
),
)
.subcommand(SubCommand::with_name("setup").about("Configure Oxidux"))
.setting(AppSettings::SubcommandRequiredElseHelp)
.get_matches();

Expand All @@ -60,6 +60,9 @@ fn main() -> color_eyre::Result<()> {
let app_name = matches.value_of("app_name");
oxidux::client::stop_app(app_name)?;
}
("setup", Some(_matches)) => {
oxidux::setup::setup();
}
(command, _) => panic!("Unrecognized command {}", command),
}

Expand Down
112 changes: 112 additions & 0 deletions src/setup.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
use std::fs::{create_dir, File};
use std::io::Write;
use std::path::PathBuf;
use std::process::Command;

use eyre::{bail, eyre, WrapErr};
use hyper::Client;
use nix::unistd::User;

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "linux")]
use linux as imp;

#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "macos")]
use macos as imp;

pub fn setup() {
println!("Welcome to Oxidux!");
if let Err(e) = try_setup() {
eprintln!("Error: {:?}", e);
eprintln!("Aborting setup");
} else {
println!("Setup complete");
}
}

type SetupResult = color_eyre::Result<()>;

struct SetupArgs {
domain: String,
home_dir: PathBuf,
config_file: PathBuf,
user: String,
}

fn try_setup() -> SetupResult {
let domain = dialoguer::Input::new()
.with_prompt("Top level domain for your apps")
.default(crate::config::default_domain())
.interact_text()
.context("Domain input failed")?;

verify_tmux()?;

let user = std::env::var("SUDO_USER").context("Unable to determine user account")?;
let home_dir = User::from_name(&user)?
.ok_or_else(|| eyre!("User has no configured home directory"))?
.dir;
let config_dir = home_dir.join(".oxidux");
if !config_dir.is_dir() {
create_dir(&config_dir)?;
}
let config_file = config_dir.join("config.toml");

let args = SetupArgs {
domain,
home_dir,
config_file,
user,
};

write_config(&args)?;

imp::setup(&args)?;

test_connection(&args)?;

Ok(())
}

fn verify_tmux() -> SetupResult {
println!("Checking for tmux command");
let result = Command::new("tmux").arg("-V").status();

if let Ok(status) = result {
if status.success() {
return Ok(());
}
}

bail!("Tmux command not found\nPlease install tmux before proceeding")
}

#[tokio::main]
async fn test_connection(args: &SetupArgs) -> SetupResult {
let url = format!("http://connection-test.{}/", args.domain);
println!("Checking connection to {}", url);

let response = Client::new().get(url.parse()?).await?;

let bytes = hyper::body::to_bytes(response.into_body()).await?;
let body = std::str::from_utf8(&bytes)?;

if body.contains("App not found") {
Ok(())
} else {
bail!("Unexpected response body\n {}", body)
}
}

fn write_config(args: &SetupArgs) -> SetupResult {
println!("Writing config to {}", args.config_file.to_string_lossy());
let toml = format!("[general]\ndomain = \"{}\"", args.domain);

let mut config_file = File::create(&args.config_file)?;
config_file.write_all(&toml.as_bytes())?;

Ok(())
}
Loading