#export PATH=$PATH:$GOPATH/bin:~/bin:~/.cargo/bin

export EDITOR=vi

# Improve readability of `ls`
export TIME_STYLE=long-iso
export BLOCK_SIZE="'1"

alias grep=grep --color=auto
if { os linux } then { alias ls=ls --color=auto }

if { which vim } then { alias vi=vim }

# https://github.com/sharkdp/bat
if { which bat } then {
    alias cat=bat
    summary cat ${man-summary cat}
}

# https://github.com/sharkdp/lsd
# https://github.com/ryanoasis/nerd-fonts/
#if { which lsd } then { 
#    alias ls=lsd
#    summary ls ${man-summary ls}
#}

function pless {
    # less for JSON
    -> trypipe { -> pretty -> less }
}

function chdir {
    # make a directory then change to that new dir (assumes `-p` flag where supported)
    try {
        switch ${os} {
            case windows { tout json {} }
            case linux   { tout json {[ "-p", "--" ]} }
            catch        { tout json {[ "-p" ]} }
        } -> set flags

        mkdir @flags $ARGS[1]
        cd $ARGS[1]
    }
}

config set shell hint-text-func {
    trypipe <!null> {
        git status --porcelain -b -> set gitstatus
        #$gitstatus -> head -n1 -> sed -r 's/^## //;s/\.\.\./ => /' -> set gitbranch
        $gitstatus -> head -n1 -> regexp 's/^## //' -> regexp 's/\.\.\./ => /' -> set gitbranch
        let gitchanges=${ out $gitstatus -> sed 1d -> wc -l }
        !if { $gitchanges } then { ({GREEN}) } else { ({RED}) }
        (Git{BLUE}: $gitbranch ($gitchanges pending). )
    }
    catch {
        ({YELLOW}Git{BLUE}: Not a git repository. )
    }

    if { $SSH_AGENT_PID } then {
        ({GREEN}ssh-agent{BLUE}: $SSH_AGENT_PID. )
    } else {
        ({RED}ssh-agent{BLUE}: No env set. ) 
    }
    
    if { pgrep: vpnc } then {
        ({YELLOW}VPN{BLUE}: vpnc is active. )
    }

    if { ps aux -> regexp m/openvpn --errors-to-stderr --log/ } then {
        ({YELLOW}VPN{BLUE}: openvpn is active. )
    }
    
    trypipe <!null> {
        open: main.tf -> format json -> [ terraform ] -> [ 0 ] -> [ required_version ] -> sed -r 's/\s0\./ /' -> set tfmod
        terraform: version -> head -n1 -> regexp (f/Terraform v0\.([0-9.]+)$) -> set tfver
        if { = tfmod >= tfver } then { ({GREEN}) } else { ({RED}) }
        (Terraform{BLUE}: $tfver; required $tfmod. )
    }
    
    if { $AWS_SESSION_TOKEN } then {
        set aws_expiration
        set int date=${ date +%s }

        if { os linux } then {
            set int aws_expiration=${ date -d $AWS_SESSION_EXPIRATION +%s }
        } else {
            set int aws_expiration=${ date -j -f "%FT%R:%SZ" $AWS_SESSION_EXPIRATION +%s }
        }

        = (($aws_expiration-$date)/60) -> format int -> set aws_session_time
        if { = aws_session_time < 1 } then { ({RED}) } else { ({GREEN}) }
        (awscon{BLUE}: $AWS_SESSION_NAME => $aws_session_time mins. )
    }
}

############
## AWSCON ##
############

if { g: ~/dev/python/infra-aws-assume-role/aws_assume_role.py } then {

    function awscon {
        # Authenticates with AWS using multi-factor authentication
        $ARGS -> [ <!null> 2 ] -> set mfatoken
        try {
            if { $mfatoken } else {
                read mfatoken "Please enter the 6 digit AWS identities MFA: "
            }
            python ~/dev/python/infra-aws-assume-role/aws_assume_role.py --profile $ARGS[1] --MFAtoken $mfatoken -> source
        }
    }

    autocomplete set awscon { [{
        "Dynamic": ({
            trypipe {
                open terraform.tfvars -> [ aws_account_id ] -> set accid
                grep $accid ~/.aws/config -n -> regexp 'f/(^[0-9]+)' -> set int line
                let line=line-3
                cat ~/.aws/config -> @[$line..$line]n -> regexp 'f/^\[profile (.*?)\]/'
            }; catch {
                cat ~/.aws/config -> regexp 'f/^\[profile (.*?)\]/' -> sort
            }
        })
    }] }

}

#############
## KEYBASE ##
#############

autocomplete set keybase { [{
    "DynamicDesc": ({
        #keybase: -> @[ ^COMMANDS:\$..^\$ ]re -> sort -> set keybase
        #map { $keybase[ :0 ] -> regexp s/,// } { $keybase -> regexp 'f/\t+(.*?)$' }
        keybase -> @[^COMMANDS..^ADDITIONAL]re -> tabulate: --split-comma --map
    }),
    "ListView": true,
    "FlagValues": {
        "pgp": [{
            "DynamicDesc": ({
                keybase help pgp -> @[^COMMANDS..^ADDITIONAL]re -> tabulate: --split-comma --map
            }),
            "ListView": true
        }]
    }
}] }

###############
## CONCOURSE ##
###############

summary fly "Concourse - The `fly` CLI"
autocomplete set fly {
    [
        {
            "DynamicDesc": ({
                fly -> match: -- -> set fly
                map {
                    $fly: -> regexp: (f/(--.*?)[\s\t])
                } {
                    $fly: -> regexp: (m/--/) -> regexp: (f/--.*? +(.*))
                }
            }),
            "Optional": true,
            "AllowMultiple": true

        },
        {
            "DynamicDesc": ({
                fly -> @[Available commands:..]se -> set fly
                map { $fly[:0] } { $fly -> regexp 'f/^ +.*? +(.*?)$/' -> regexp 's/\(.*?\)//'}
            }),
            "AllowMultiple": true,
            "AllowOther": true
        }
    ]
}
