#use sops/lib.nu on_sops

# -  > SOPS   with infrastructure and services
export def "main sops" [
  sourcefile?: string # source file for sops command
  targetfile?: string # target file for sops command
  --encrypt (-e)      # SOPS encrypt file 
  --decrypt (-d)      # SOPS decrypt file
  --gen (-g)          # SOPS generate encrypted files 
  --sed               # Edit sops encrypted 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 "sops" --end
  if $debug { $env.PROVISIONING_DEBUG = true } 
  if $sourcefile == "sed" or $sourcefile == "ed" {
    on_sops "sed" $targetfile
    end_run "sops"
    return true
  }
  if $sed and $sourcefile != null and ($sourcefile | path exists) {
    on_sops sed $sourcefile
    exit
  }
  if $encrypt {
    if $sourcefile == null or not ($sourcefile | path exists) {
      print $"🛑 Error on_sops encrypt 'sourcefile' ($sourcefile) not found "
      exit 1
    }
    if ($targetfile | is-not-empty) {
      print $"on_sops encrypt ($sourcefile) ($targetfile)"
      on_sops "encrypt" $sourcefile $targetfile 
      exit 
    } else {
      print $"on_sops encrypt ($sourcefile) "
      print (on_sops "encrypt" $sourcefile)
      exit 
    }
  }
  if $decrypt {
    if $sourcefile == null or not ($sourcefile | path exists) {
      print $"🛑 Error on_sops decrypt 'sourcefile' ($sourcefile) not found "
      return false
    } 
    if ($targetfile | is-not-empty) {
      on_sops decrypt $sourcefile $targetfile
      exit 
    } else { 
      print (on_sops decrypt $sourcefile)
      exit 
    }
  }
  if $gen and $sourcefile != null {
    on_sops generate $sourcefile $targetfile
    exit
  }
  option_undefined "sops" "" 
  #cleanup $settings.wk_path
  end_run "sops"
}
