#!/usr/bin/env nu 
# Info: Prepare for coredns installation
# Author: JesusPerezLorenzo 
# Release: 1.0.2
# Date: 26-02-2024

use lib_provisioning/cmd/env.nu * 
use lib_provisioning/cmd/lib.nu *

use lib_provisioning/utils/ui.nu *

print $"(_ansi green_bold)CoreDNS(_ansi reset) with ($env.PROVISIONING_VARS) " 

let run_root = $env.PROVISIONING_WK_ENV_PATH

if $env.PROVISIONING_RESOURCES == null { 
  print $"🛑 PROVISIONING_RESOURCES not found"  
  exit 1
}

#let resources_path = ($env.PROVISIONING_SETTINGS_SRC_PATH | path join "resources")
let resources_path = ($run_root | path join "resources")

if not ($resources_path | path exists) {  ^mkdir -p $resources_path  }

if not ($resources_path | path exists) {
  print $"🛑 Path ($resources_path | path dirname) not found"  
  exit 1
}

let dns_tpl = ($run_root | path join "dns.tpl")
if not ($dns_tpl | path exists) {
  print $"🛑 dns.tpl not found in ($run_root)"  
  exit 1
}

let defs = load_defs

$defs.taskserv.entries | enumerate | each {|it| 
  let filename = ($it.item | get -i file | default "")
  let domain = ($it.item |  get -i domain | default "")
  if $filename != "" and $domain != "" {
    let resources_filename_path = ($resources_path | path join $"($filename | path basename).j2")
    cp $dns_tpl $resources_filename_path
    if not ($resources_filename_path | path exists) {
      print $"🛑 Path ($resources_filename_path) not found for ($it.index)"  
      exit 1
    }
   (open -r $resources_filename_path | str replace --all "DOMAIN_NAME" $domain | str replace --all "DOMAIN_POS" $"($it.index)" 
     | save --force $resources_filename_path )
    #^sed -i $"\"s/DOMAIN_NAME/($domain)/g\"" $resources_filename_path
    #^sed -i $"\"s/DOMAIN_POS/($it.index)/g\"" $resources_filename_path
    # Clean up and compact lines
    #^sed -i -e '/\S/!d' $resources_filename_path  #2>/dev/null
  }
}