#!/usr/bin/env nu

# Ensure we are located at the bin folder
const current_folder = path self | path dirname | path dirname
cd $current_folder

def valid_profiles [] {
	nix eval .#nixosConfigurations --apply 'builtins.attrNames' --json err> /dev/null |
        from json
}

def valid_remote_profiles [] {
	(valid_profiles) | where {|$it | str starts-with "hl" }
}

def is-valid-profile [name: string, on_remote: bool = false] {
    if $on_remote {
        (valid_remote_profiles | where {|$it| $it == $name} | length) == 1
    } else {
        (valid_profiles | where {|$it| $it == $name} | length) == 1
    }
}

def main [] {
		print $current_folder
    help main
}

def "main profiles" [only_remote: bool = false] {
    if $only_remote {
        valid_remote_profiles | print
    } else {
        valid_profiles | print
    }
}

# Build configuration
def "main build" [] {
    nh os build | print
}

# Switch configuration
def "main switch" [] {
    nh os switch --ask | print
}

# test configuration
def "main test" [] {
    nh os test | print
}

# rollback configuration
def "main rollback" [] {
    sudo nixos-rebuild switch --rollback
}

# update some flakes
def "main update" [input_name:string = ""] {
    if $input_name == "" {
        print "Updating all flakes..."
        nix flake update | print
    } else {
        print "Updating flake: $input_name"
        nix flake update $input_name | print
    }
    git diff flake.lock | print
}

# Deploy to remote machine
def "main remote" [cmd:string, target:string = ""] {
    mut target_host = $"root@($target).lab.internal"
    mut profile = $"hl-($target)"
    if not (is-valid-profile $profile true) {
        print $"Invalid Remote Profile '(ansi green_bold)($target)(ansi reset)', please select one of:"
        return (valid_remote_profiles | each {|p| $p | str replace "hl-" ""})
    }
    $"Using [(ansi green_bold)($profile)(ansi reset)]" | print
    const valid_cmds = [
        "test" , "dry-activate" , "run" , "switch" , "build"
    ]
    if not ($cmd in $valid_cmds) {
        print $"Invalid command ($cmd), please select one of"
        return $valid_cmds
    }
    $"($cmd) on ($target_host) with ($profile)" | print
    mut runcmd = $"nh os ($cmd) --target-host ($target_host) --ask .#($profile)"
    $runcmd | print
    bash -c $runcmd
}

# Build ISO image
def "main build-iso" [] {
	nix build .#nixosConfigurations.iso.config.system.build.isoImage
	ls -l result/iso
}

# Home Manager operations
def "main hm" [action: string@hm-actions, profile: string = "ari"] {
    let valid_actions = (hm-actions)
    if not ($action in $valid_actions) {
        error make {
            msg: $"Invalid action '($action)'",
            help: $"Valid actions are: ($valid_actions | str join ', ')"
        }
    }
    $"Running home-manager ($action) for profile ($profile)" | print
    home-manager $action --flake $".#($profile)"
}

def hm-actions [] {
    ["switch", "build"]
}
