#!/bin/env fish
begin
    set -l dir (status dirname)
    source "$(status dirname)/../../Scripts/software.fish"

    function configureSW -S -V dir
        source "$dir/../../Scripts/config.fish"
        set -l branch "valhalla.git.defaultBranch"

        function setConfig
            sudo git config --system $argv
        end

        if isSet "$branch"
            setConfig init.defaultBranch (getConfig "$branch")
        end

        setConfig user.name "Manuel Thalmann"
        setConfig user.email "m@nuth.ch"

        begin # Git Flow
            set -l dir (mktemp -d)

            pushd "$dir" > /dev/null
            begin
                set -l key valhalla.git.flow
                set -l mainKey "$key.mainBranch"
                set -l devKey "$key.devBranch"

                git init
                git commit --allow-empty -m "Initial commit" > /dev/null
                git branch master || true &> /dev/null
                git branch main || true &> /dev/null
                git branch dev || true &> /dev/null
                yes "" | git flow init &> /dev/null

                if isSet "$mainKey"
                    sudo git flow config set --system master (getConfig "$mainKey") > /dev/null
                else
                    true
                end

                if isSet "$devKey"
                    sudo git flow config set --system develop (getConfig "$devKey") > /dev/null
                else
                    true
                end
            end
            popd > /dev/null

            rm -rf "$dir"
        end

        begin # Aliases
            set -l key valhalla.git.aliases
            set -l aliases (getConfig "$key" --json)

            for name in (echo "$aliases" | jq 'keys[]' --raw-output0 | string split0)
                setConfig "alias.$name" (getConfig "$key.$name")
            end
        end
    end
end