# Import will be handled by parent context

# -  > Secrets management with infrastructure and services (SOPS or KMS)
export def "main secrets" [
  sourcefile?: string # source file for secrets command
  targetfile?: string # target file for secrets command
  --provider (-p): string # secret provider: sops or kms
  --encrypt (-e)      # Encrypt file 
  --decrypt (-d)      # Decrypt file
  --gen (-g)          # Generate encrypted files 
  --sed               # Edit encrypted file 
  --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 
  --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
  }
  
  # Set secret provider if specified
  if ($provider | is-not-empty) {
    $env.PROVISIONING_SECRET_PROVIDER = $provider
  }
  
  parse_help_command "secrets" --end
  if $debug { $env.PROVISIONING_DEBUG = true } 
  
  if $sourcefile == "sed" or $sourcefile == "ed" {
    on_secrets "sed" $targetfile
    end_run "secrets"
    return true
  }
  
  if $sed and $sourcefile != null and ($sourcefile | path exists) {
    on_secrets sed $sourcefile
    exit
  }
  
  if $encrypt {
    if $sourcefile == null or not ($sourcefile | path exists) {
      print $"🛑 Error on_secrets encrypt 'sourcefile' ($sourcefile) not found "
      exit 1
    }
    if ($targetfile | is-not-empty) {
      print $"on_secrets encrypt ($sourcefile) ($targetfile)"
      on_secrets "encrypt" $sourcefile $targetfile 
      exit 
    } else {
      print $"on_secrets encrypt ($sourcefile) "
      print (on_secrets "encrypt" $sourcefile)
      exit 
    }
  }
  
  if $decrypt {
    if $sourcefile == null or not ($sourcefile | path exists) {
      print $"🛑 Error on_secrets decrypt 'sourcefile' ($sourcefile) not found "
      return false
    } 
    if ($targetfile | is-not-empty) {
      on_secrets decrypt $sourcefile $targetfile
      exit 
    } else { 
      print (on_secrets decrypt $sourcefile)
      exit 
    }
  }
  
  if $gen and $sourcefile != null {
    on_secrets generate $sourcefile $targetfile
    exit
  }
  
  option_undefined "secrets" "" 
  end_run "secrets"
}