function google() {
    open -na "Google Chrome" --args "https://www.google.com/search?q=$*"
}
function stackoverflow() {
    open -na "Google Chrome" --args "https://www.google.com/search?q=site:stackoverflow.com $*"
}
function github() {
    open -na "Google Chrome" --args "https://github.com/search?q=$*"
}
function hacker() {
    open -na "Google Chrome" --args "https://hn.algolia.com/?sort=byDate&query=$*"
}
function gmail() {
    open -na "Google Chrome" --args "https://mail.google.com/mail/u/0"
}
function gmail2() {
    open -na "Google Chrome" --args "https://mail.google.com/mail/u/1"
}
function cicd() {
    open -na "Google Chrome" --args "https://issues.collibra.com/secure/RapidBoard.jspa?rapidView=457&view=planning.nodetail"
}
function issues() {
    jira issue jql "status = Open AND text ~ \"$*\" ORDER BY Created DESC"
}
function calendar() {
    open -na "Google Chrome" --args "https://calendar.google.com/calendar/r?tab=mc"
}
function asana() {
    open -na "Google Chrome" --args "https://app.asana.com"
}
function bookmarks() {
    open -na "Google Chrome" --args "https://github.com/MorganGeek/bookmarks/blob/master/README.md"
}
function spotify() {
    open -na "Google Chrome" --args "https://open.spotify.com/search/$*"
}
function lob() {
    open -na "Google Chrome" --args "https://lobste.rs"
}
function logtalk() {
    path_swilgt=$(find /usr/local/Cellar/logtalk -name "*swilgt.sh" 2>/dev/null)
    sh "$path_swilgt"
}
function archive() {
    open -na "Google Chrome" --args "https://web.archive.org/web/*/$*"
}
function git_listobjectsbysize() {
    tempFile=$(mktemp)
    IFS=$'\n'
    for commitSHA1 in $(git rev-list --all); do
        git ls-tree -r --long "$commitSHA1" >>"$tempFile"
    done

    # sort files by SHA1, de-dupe list and finally re-sort by filesize
    sort --key 3 "$tempFile" | \
        uniq | \
        sort --key 4 --numeric-sort --reverse
    # remove temp file
    rm -f "$tempFile"
}
function top_commands() {
    history | cat | awk '{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a; }' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n50
}
function top_commands_full() {
    history | cat | sed 's/^[0-9 TAB]*//g' | awk '{CMD[$0]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "%\t" a; }' | sort -nr | nl | head -n50
}
function istherenewissues() {
    LASTISSUE=$(newissues | sed $'s,\x1b\\[[0-9;]*[a-zA-Z],,g' | awk 'FNR==2{print $2}')
    if [[ -f "$HOME/.newjiraissue" ]]
    then
        previous_jira_issue=$(cat "$HOME/.newjiraissue" | sed $'s,\x1b\\[[0-9;]*[a-zA-Z],,g') # the sed part is for removing output colors
        if [ "$LASTISSUE" != "$previous_jira_issue" ]; then
            newissues
        else
            echo "no new issue"
        fi
    fi
    echo "$LASTISSUE" > "$HOME/.newjiraissue"
}
function aboutpage() {
    year=$(echo "$*" | egrep -Eo '\b[[:digit:]]{4}\b' | head -n1)
    if [ -z "$year" ]
    then
        year=$(curl -sSL "$*" | tr '<' '\r' | \egrep -i "date|datetime" -A 1 | \grep -Eo '\b[[:digit:]]{4}\b' | head -n1)
    fi
    author=$(curl -sSL "$*" | tr '<' '\r' | \egrep -i "author" -A 1 | \grep -Eo '([A-Z][A-Za-z]+\s([A-Za-z ]+)*)' | head -n1)
    title=$(curl -sSL "$*" | tr '<' '<\n' | \grep title -A 1 | head -n1 | sed -E 's/.*<title>(.*)<\/title>.*/\1/' | sed "s/ [^[:alnum:]]*$author//")
    yearint=$(($year + 0))
    currentyear=$(echo `date +"%Y"`)
    if [ ! -z "$author" ]
    then
        echo "by $author"
    fi
    if [ ! -z "$title" ]
    then
        echo "-> $title"
    fi
    if [[ $yearint -ge 1970 && $yearint -le $currentyear ]]
    then
        echo "$yearint"
    fi
    if [ ! -z "$title" ] && [ ! -z "$author" ] && [[ $yearint -ge 1970 && $yearint -le $currentyear ]]; then
        echo "[$author]($*) - ($yearint) $title"
    fi
}

# Extract a column from a tabular output
# via https://blog.developer.atlassian.com/ten-tips-for-wonderful-bash-productivity/
function col() {
    awk -v col=$1 '{print $col}'
}
# Skip first x words in line
# via https://blog.developer.atlassian.com/ten-tips-for-wonderful-bash-productivity/
function skip {
    n=$(($1 + 1))
    cut -d' ' -f$n-
}

cmd_loc="find . -type f \( \
        -name '*.py' \
        -o -name '*.rb' \
        -o -name '*.go' \
        -o -name '*.java' \
        -o -name '*.kt' \
        -o -name '*.c' -o -name '*.h' \
        -o -name '*.js' \
        -o -name '*.tsx' \
        -o -name '*.md' \
        -o -name '*.xml' \
        -o -name '*.groovy' \
        -o -name '*.gradle' \
        -o -name '*.properties' \
        \)  -exec \cat \{\} \; | LANG=C LC_CTYPE=C sed -e 's/^[ \t]*//;s/[ \t]*$//'"

# Unique lines of code
# Via https://text.causal.agency/004-uloc.txt
function uloc {
    eval "$cmd_loc | LANG=C LC_CTYPE=C sort -u | wc -l"
}

# Top lines of code
function toploc {
    eval "$cmd_loc | LANG=C LC_CTYPE=C cut -c 1-100 | LANG=C LC_CTYPE=C sort | uniq -c | LANG=C LC_CTYPE=C sort -nr"
}

# Find files bigger than X size and sort them by size
function biggerthan() {
    find . -size "+$*" -type f -print0 | xargs -0 ls -Ssh | sort -z
}
# To automatically ls when changing directory
function cd() {
    builtin cd "$@" && ls -latr
}
function mouse() {
    case "$(uname -s)" in
        Darwin)
            sh ~/.scripts/mouse_bluetooth.sh
            ;;
    esac
}
function meteo() {
    curl "fr.wttr.in/$*"
}
function how_in() {
    where="$1"; shift
    IFS=+ curl "cht.sh/${where}/$*"
}
function rate() {
    curl "http://rate.sx/$*"
}
transfer() {
    # check arguments
    if [ $# -eq 0 ];
    then
        echo "No arguments specified. Usage:\necho transfer /tmp/test.md\ncat /tmp/test.md | transfer test.md"
        return 1
    fi

    # get temporarily filename, output is written to this file show progress can be showed
    tmpfile=$( mktemp -t transferXXX )

    # upload stdin or file
    file=$1

    if tty -s;
    then
        basefile=$(basename "$file" | sed -e 's/[^a-zA-Z0-9._-]/-/g')

        if [ ! -e $file ];
        then
            echo "File $file doesn't exists."
            return 1
        fi

        if [ -d $file ];
        then
            # zip directory and transfer
            zipfile=$( mktemp -t transferXXX.zip )
            cd $(dirname $file) && zip -r -q - $(basename $file) >> $zipfile
            curl --progress-bar --upload-file "$zipfile" "https://transfer.sh/$basefile.zip" >> $tmpfile
            rm -f $zipfile
        else
            # transfer file
            curl --progress-bar --upload-file "$file" "https://transfer.sh/$basefile" >> $tmpfile
        fi
    else
        # transfer pipe
        curl --progress-bar --upload-file "-" "https://transfer.sh/$file" >> $tmpfile
    fi
    # cat output link
    cat $tmpfile

    # cleanup
    rm -f $tmpfile
}
# Where is a function defined?
function whichfunc() {
    whence -v $1
    type -a $1
}

# git shortcuts
function gcrb {
   branch=$1
   git checkout -b $branch origin/$branch
}
function terraform-compliance { docker run --rm -v "$(pwd):/target" -i -t eerkunt/terraform-compliance "$@"; }
function checkov { docker run -i --rm -v "$(pwd):/tf" bridgecrew/checkov -d /tf "$@" ; }
function vimat {
    vim +/$1 $2
}
function copyhooks {
   cp -f ~/.git-template/.pre-commit-config.yaml ./
   pre-commit install --install-hooks --overwrite
   pre-commit run -a
}
function httperr {
   curl -s "https://http.cat/$1" | imgcat
}
function terragrunt_color {
    BOLD=$(tput bold)
    BLACK=$(tput setaf 0)
    RED=$(tput setaf 1)
    GREEN=$(tput setaf 2)
    YELLOW=$(tput setaf 3)
    BLUE=$(tput setaf 4)
    CYAN=$(tput setaf 6)
    RESET=$(tput sgr0)
    REDBOLD=${RED}${BOLD}
    REDRESET=${RESET}${RED}
    BLUEBOLD=${BLUE}${BOLD}
    BLUERESET=${RESET}${BLUE}

    terragrunt ${*} 2>&1 | sed \
        -e "s/\(\\[terragrunt\\] \\[.*\\]\)\( [0-9\\/]* [0-9:]*\) /${BLUEBOLD}\1${BLUERESET}\2${RESET} /" \
        -e "s/\(\\[terragrunt\\]\)\( [0-9\\/]* [0-9:]*\) /${BLUEBOLD}\1${BLUERESET}\2${RESET} /" \
        -e "s/\(Error: \)\(.*\)/${REDBOLD}\1${REDRESET}\2${RESET}/" \
        -e "s/\(Hit multiple errors:\)/${REDBOLD}\1${RESET}/" \
        -e "s/\(exit status 1\)/${RED}\1${RESET}/" \
        -e "s/\( WARNING: \)\(.*\)/${YELLOW}${BOLD}\1${RESET}${YELLOW}\2${RESET}/" \
        -e "s/\( Running command: \)\(.*\)/\1${CYAN}\2${RESET}/" \
        -e "s/\(  *.*:  *\)\(\".*\"\)\( => \)\(\".*\"\)/${YELLOW}\1${RED}\2${BLACK}\3${GREEN}\4${RESET}/" \
        -e "s/\(  *.*:  *\".*\"\)/${GREEN}\1${RESET}/"
}
function git-project {
    if [ -d "$REPO_PATH" ]; then
        REPO_PATH="$(pwd)"
    fi
    local preview='lsd --color always --icon always --group-dirs first {}'
    local dir=$(find $REPO_PATH -maxdepth 3 -type d -name ".git" | sed 's#.git$##' | fzf --select-1 --query="$*" --preview "$preview")
    if [[ -n "$dir" ]]; then
        cd "$dir"
    fi
}