#!/usr/bin/env nu

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

def main [] {
    let defs = load_defs
    let work_path = $env.PROVISIONING_WK_ENV_PATH

    _create_directories $work_path
    _setup_git_config $work_path
    _setup_runner_token $work_path
}

# Create required directory structure for Forgejo
def _create_directories [work_path: string] {
    let dirs = [
        ($work_path + "/.forgejo"),
        ($work_path + "/data"),
        ($work_path + "/repos"),
        ($work_path + "/config"),
        ($work_path + "/ssh"),
        ($work_path + "/log"),
        ($work_path + "/custom"),
        ($work_path + "/avatars"),
        ($work_path + "/attachments"),
        ($work_path + "/lfs"),
    ]

    for dir in $dirs {
        if not ($dir | path exists) {
            mkdir -p $dir
            print $"Created directory: ($dir)"
        }
    }
}

# Setup Git configuration for Forgejo
def _setup_git_config [work_path: string] {
    let git_config = ($work_path + "/config/git.config")

    if not ($git_config | path exists) {
        let config_content = @"
[core]
    sshCommand = ssh -i /var/lib/forgejo/.ssh/id_rsa -o StrictHostKeyChecking=no
    symlinks = false
    autocrlf = false
    eol = lf

[pack]
    deltaCacheSize = 2047m
    packSizeLimit = 3g
    compression = 0

[receive]
    fsckObjects = true

[uploadpack]
    allowAnySHA1InWant = true
    allowReachableSHA1InWant = true
"@

        $config_content | save -f $git_config
        print $"Created Git configuration: ($git_config)"
    }
}

# Setup runner token if Woodpecker CI integration is configured
def _setup_runner_token [work_path: string] {
    let token_file = ($work_path + "/config/runner.token")

    if ($env | get -i FORGEJO_RUNNER_TOKEN | is-not-empty) {
        $env.FORGEJO_RUNNER_TOKEN | save -f $token_file
        chmod 600 $token_file
        print "Stored Forgejo Runner token"
    }
}
