#!/usr/bin/env nu
# Info: Script to run Provisioning
# Author: JesusPerezLorenzo
# Release: 1.0.4
# Date: 6-2-2024

#use std  # assert
use std log

use lib_provisioning *

use env.nu *

use servers *

# - > Help on Server
export def "main help" [
  --src: string = ""
  --notitles       # not tittles
  --out: string    #  Print Output format: json, yaml, text (default)
]: nothing -> nothing {
  if $notitles == null or not $notitles { show_titles }
  ^$"($env.PROVISIONING_NAME)" -mod server --help
  if ($out | is-not-empty) { $env.PROVISIONING_NO_TERMINAL = false }
  print (provisioning_options $src)
  if not $env.PROVISIONING_DEBUG { end_run "" }
}

# >  Server
def main [
  ...args: string  # Other options, use help to get info
  -v               # Show version
  -i               # Show Info
  --version (-V)   # Show version with title
  --info (-I)      # Show Info  with title
  --about (-a)     # Show About
  --infra (-i): string  # Infra directory
  --settings (-s): string # Settings path
  --serverpos (-p): int   # Server position in settings
  --outfile (-o): string  # Output file
  --yes (-y)       # Confirm task
  --check (-c)     # Only check mode no servers will be created
  --wait (-w)      # Wait servers to be created
  --keepstorage    # keep storage
  --select: string # Select with task as option
  --onsel: string  # On selection: e (edit) | v (view) | l (list)
  --debug (-x)     # Use Debug mode
  --xm             # Debug with PROVISIONING_METADATA
  --xc             # Debug 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
  --nc             # Not clean working settings
  --metadata       # Error with metadata (-xm)
  --notitles       # Do not show banner titles
  --helpinfo (-h)  # For more details use options "help" (no dashes)
  --out: string    #  Print Output format: json, yaml, text (default)
  --include_notuse # Include servers not use
]: nothing -> nothing {
  if ($out | is-not-empty) {
    $env.PROVISIONING_OUT = $out
    $env.PROVISIONING_NO_TERMINAL = true
  }
  provisioning_init $helpinfo "server" $args
  if $version or $v { ^$env.PROVISIONING_NAME -v ; exit }
  if $info or $i { ^$env.PROVISIONING_NAME -i ; exit }
  if $about {
    #use defs/about.nu [ about_info ]
    _print (get_about_info)
    exit
  }
  if $debug { $env.PROVISIONING_DEBUG = true }
  if $metadata { $env.PROVISIONING_METADATA = true }
  # DEBUG: Print received args
  if ($env.PROVISIONING_DEBUG? | default false) {
    print $"DEBUG provisioning server: args length = ($args | length)" >&2
    for arg in $args { print $"DEBUG provisioning server: arg = '($arg)'" >&2 }
  }
  let task = if ($args | length) > 0 { ($args| get 0) } else { "" }
  let ops = if ($args | length) > 1 { ($args | skip 1 | str join " ") } else { "" }
  if ($env.PROVISIONING_DEBUG? | default false) {
    print $"DEBUG provisioning server: task = '($task)', ops = '($ops)'" >&2
  }
  $env.PROVISIONING_MODULE = "server"
  match $task {
    "upcloud" => {
      #use upcloud/servers.nu upcloud
      if $infra == null {
        upcloud $args
      } else {
        upcloud --infra $infra $args
      }
    },
    "aws" => { aws $args },
    "local" => { local $args },
    "providers" => {
      #use defs/lists.nu *
      print $"(_ansi green)PROVIDERS(_ansi reset) list: \n"
      print (providers_list "selection" | table -i false )
    },
    "h" | "help" => {
      # Redirect to main categorized help system
      exec $"($env.PROVISIONING_NAME)" help infrastructure --notitles
    },
    "ssh" => {
      #use servers/ssh.nu *
      #use utils/settings.nu *
      let curr_settings = (find_get_settings --infra $infra --settings $settings $include_notuse)
      server_ssh $curr_settings "" "pub" false
    },
    "status" => {
      let out_str = if ($out | is-not-empty)  {
        $"--out ($out)"
      } else {
        ""
      }
      exec ($env.PROVISIONING_NAME) "-mod" "server" "status" ...($ops | split row " ") $out_str --notitles
    }
    "sed" => {
      let str_ops = ($ops | split row " " | get -o 0 |  str trim)
      if $str_ops == "" {
        (throw-error $"🛑 No file found" $"for (_ansi yellow_bold)sops(_ansi reset) edit")
        exit 1
      } else if ($str_ops | path exists) == false {
        (throw-error $"🛑 No file (_ansi green_italic)($str_ops)(_ansi reset) found" $"for (_ansi yellow_bold)sops(_ansi reset) edit")
        exit 1
      }
      if $env.PROVISIONING_SOPS? == null  {
        let curr_settings = (find_get_settings --infra $infra --settings $settings $include_notuse)
        $env.CURRENT_INFRA_PATH = ($curr_settings.infra_path | path join $curr_settings.infra)
        rm -rf $curr_settings.wk_path
        use sops_env.nu
      }
      #use sops on_sops
      on_sops "sed" $str_ops
    },
    "cache" => {
      provider_data_cache (find_get_settings --infra $infra --settings $settings $include_notuse) --outfile $outfile
    },
    "c" | "create" => {
      exec ($env.PROVISIONING_NAME) "-mod" "server" "create" ...($ops | split row " ") --notitles
    },
    "s" | "status" => {
      exec ($env.PROVISIONING_NAME) "-mod" "server" "status" ...($ops | split row " ") --notitles
    },
    "stop" => {
      let use_wait = if $wait { "--wait" } else { "" }
      exec ($env.PROVISIONING_NAME) "-mod" "server" "state" "stop" ...($ops | split row " ") ($use_wait) --notitles
    },
    "start" => {
      let use_wait = if $wait { "--wait" } else { "" }
      exec ($env.PROVISIONING_NAME) "-mod" "server" "state" "start" ...($ops | split row " ") ($use_wait) --notitles
    },
    "r" | "rs" | "restart" | "reboot" => {
      let use_wait = if $wait { "--wait" } else { "" }
      exec ($env.PROVISIONING_NAME) "-mod" "server" "state" "restart" ...($ops | split row " ") ($use_wait) --notitles
    },
    "d" | "delete" => {
      let use_yes = if $yes { "--yes" } else { "" }
      exec ($env.PROVISIONING_NAME) "-mod" "server" "delete" ...($ops | split row " ") ($use_yes) --notitles
    },
    "g" | "generate" => {
      exec ($env.PROVISIONING_NAME) "-mod" "server" "generate" ...($ops | split row " ") --notitles
    }
    "ds" | "delete-storage" => {
      let use_yes = if $yes { "--yes" } else { "" }
      exec ($env.PROVISIONING_NAME) "-mod" "server" "delete" "storage" ...($ops | split row " ") ($use_yes) --notitles
    },
    "price" | "prices" | "cost" | "costs" => {
      let hostname = if ($ops | str starts-with "-") or ($ops | str starts-with "price") or ($ops | str starts-with "cost") {
        ""
      } else {
        ($ops | split row "-" | find -v -r "^--" | get -o 0 | default "")
      }
      let match_host = if ($hostname | str starts-with "-") {
          ""
      } else {
        $hostname
      }
      let curr_settings = (find_get_settings --infra $infra --settings $settings $include_notuse)
      servers_walk_by_costs $curr_settings $match_host $check false $outfile
      rm -rf $curr_settings.wk_path
    },
    "list" => {
      #use defs/lists.nu on_list
      on_list "providers" ($onsel | default "") ""
    },
    "qr" => {
      #use utils/qr.nu *
      make_qr
    },
    _ => {
      invalid_task "server" $task --end
    },
  }
  if not $env.PROVISIONING_DEBUG { end_run "" }
}
