
def prompt_update [
  target: string 
  target_name: string 
  yes: bool
  name?: string
]: nothing -> string {
  match $name {
    "h" | "help" => {
      ^($env.PROVISIONING_NAME) "-mod" $target "--help"
      exit 0
    }
  }
  if not $yes or not (($env.PROVISIONING_ARGS? | default "") | str contains "--yes")  {
    _print ( $"To (_ansi red_bold)update ($target_name) (_ansi reset) " +
      $" (_ansi green_bold)($name)(_ansi reset) type (_ansi green_bold)yes(_ansi reset) ? " 
    )
    let user_input = (input --numchar 3)
    if $user_input != "yes" and $user_input != "YES"  {
      exit 1
    }
    $name
  } else { 
    $env.PROVISIONING_ARGS = ($env.PROVISIONING_ARGS? | find -v "yes")
    ($name | default "" | str replace "yes" "") 
  }
}
# -> Update infrastructure and services
export def "main update" [
  target?: string     # server (s) | task (t) | service (sv)
  name?: string       # target name in settings
  ...args                 # Args for create command 
  --serverpos (-p): int   # Server position in settings 
  --keepstorage          # Keep storage
  --yes (-y)              # confirm update
  --wait (-w)             # Wait servers to be created 
  --infra (-i): string    # Infra path 
  --settings (-s): string # Settings path 
  --outfile (-o): string  # Output file
  --debug (-x)            # Use Debug mode
  --xm             # Debug with PROVISIONING_METADATA 
  --xc             # Debuc for task and services locally PROVISIONING_DEBUG_CHECK 
  --xr             # Debug for remote servers PROVISIONING_DEBUG_REMOTE 
  --xld            # Log level with DEBUG PROVISIONING_LOG_LEVEL=debug 
  --metadata       # Error with metadata (-xm)
  --notitles       # not tittles
  --out: string    # Print Output format: json, yaml, text (default)
]: nothing -> nothing {
  if ($out | is-not-empty) {
    $env.PROVISIONING_OUT = $out 
    $env.PROVISIONING_NO_TERMINAL = true
  }
  parse_help_command "update" --end
  if $debug { $env.PROVISIONING_DEBUG = true } 
  let use_debug = if $debug or $env.PROVISIONING_DEBUG { "-x" } else { "" } 
  match $target { 
    "server"| "servers" | "s" => { 
      let use_keepstorage = if $keepstorage { "--keepstorage "} else { "" }
      prompt_update "server" "servers" $yes $name
      ^$"($env.PROVISIONING_NAME)" $use_debug -mod "server" ($env.PROVISIONING_ARGS | str replace $target '') --yes --notitles $use_keepstorage
    },
    "taskserv" | "taskservs" | "t" => { 
      prompt_update "taskserv" "tasks/services" $yes $name
      ^$"($env.PROVISIONING_NAME)" $use_debug -mod "tasksrv" ($env.PROVISIONING_ARGS | str replace $target '') --yes --notitles
    },
    "clusters"| "clusters" | "cl" => { 
      prompt_update "cluster" "cluster" $yes $name
      ^$"($env.PROVISIONING_NAME)" $use_debug -mod "cluster" ($env.PROVISIONING_ARGS | str replace $target '') --yes --notitles
    },
      _ => { 
        invalid_task "update" ($target | default "") --end
        exit
    },
  }
}
