#!/bin/bash

success() {
  echo -e "\n\e[32m[SUCCESS] $1\e[0m\n"
}

info() {
  echo -e "\e[34m[INFO] $1\e[0m"
}

error() {
  echo -e "\n\e[31m[ERROR] $1\e[0m\n"
  exit 1
}

warn() {
  echo -e "\e[33m[WARN] $1\e[0m"
}

prefix="/usr/local"
[[ -n "$PREFIX" ]] && prefix="$PREFIX"

# find prefix, either /usr or /usr/local
if ! test -e "$prefix/lib/emp3r0r/emp3r0r-cc"; then
  # if not found in /usr/local then set to /usr
  prefix="/usr"
  if ! test -e "$prefix/lib/emp3r0r/emp3r0r-cc"; then
    # if still nothing, abort
    error "emp3r0r not installed, please run build.sh --install"
  fi
fi
export EMP3R0R_PREFIX="$prefix" # emp3r0r-cc will read this
data_dir="$prefix/lib/emp3r0r"
cc="$data_dir/emp3r0r-cc"
[[ -z "$HOME" ]] && error "HOME not set"
workspace="$HOME/.emp3r0r"

# workspace is ~/.emp3r0r
# ------------------
[[ -d "$workspace" ]] || mkdir -p "$workspace"
cd "$workspace" || error "Failed to enter $workspace"

# if 'emp3r0r client' is run
if [[ "$1" = "client" ]]; then
  # Run C2 server with tmux UI
  # --------------------------
  if ! command -v tmux >/dev/null 2>&1; then
    error "tmux not found"
  fi

  tmux_conf="$data_dir/tmux/.tmux.conf"
  [[ -f "$tmux_conf" ]] || error "$tmux_conf not found"

  # helper scripts for tmux status line
  [[ -d "$workspace/sh" ]] || cp -r "$data_dir/tmux/sh" "$workspace" || error "copy tmux scripts"

  # if not in a tmux session
  if [[ -z "$TMUX" ]]; then
    # if session emp3r0r exists
    if tmux has-session -t emp3r0r 2>/dev/null; then
      read -p "emp3r0r session already exists, attach to it? [y/N] " -n 1 -r
      echo
      if [[ $REPLY =~ ^[Yy]$ ]]; then
        tmux attach-session -t emp3r0r
      fi
    else
      # create tmux session with our config file
      info "Starting emp3r0r client in a new tmux session"
      tmux -f "$tmux_conf" new-session -s emp3r0r -n cc "$cc" "$@"
    fi
    exit
  fi

  # if already in a tmux session
  if [[ -n "$TMUX" ]]; then
    # rename, and source our config file
    tmux rename-window cc
    tmux rename-session emp3r0r
    tmux source-file "$tmux_conf"
    "$cc" "$@"
  fi
else
  # run command without tmux
  "$cc" "$@"
fi

