#!/bin/bash

STAGE_FILES=$(git diff --cached --name-only --diff-filter=ACM -- '*.js' '*.vue' '*.ts')

function core:debugf() {
    echo -e "\033[32m [Debug]: $@ \033[0m"
}
function core:warnf() {
    echo -e "\033[33m [Warn]: $@ \033[0m"
}
function core:errorf() {
    echo -e "\033[31m [Error]: $@ \033[0m"
}

function pre-commit:checkPrettier(){
    which prettier &> /dev/null
    echo $?
    if [[ "$?" == 1 ]]; then
        return 1
    else
        return 0
    fi
}

function pre-commit:lint:js(){
    prettier -c $1
    if [[ "$?" == "1" ]]; then
        prettier -w $1
        git add $1
    fi
}

function pre-commit:lint:ts(){
    prettier -c $1
    if [[ "$?" == "1" ]]; then
        prettier -w $1
        git add $1
    fi
}

function pre-commit:lint:vue(){
    prettier -c --parser vue $1
    if [[ "$?" == "1" ]]; then
        prettier -w --parser vue $1
        git add $1
    fi
}

function pre-commit:filetype(){
    local arr=$(echo $1 | tr "." "\n")
    local ret=''
    for _v in $arr
    do
        ret=$_v
    done
    echo $ret
}

function pre-commit:main(){
    echo 'pre-commit:main:' ${#STAGE_FILES}
    if test ${#STAGE_FILES} -gt 0
    then
        core:debugf 'run pre-commit'

        local hasPrettier=$(pre-commit:checkPrettier)
        if [[ "$hasPrettier" == "1" ]]; then
            core:errorf 'prettier has not been installed!'
            core:warnf 'please run: npm install prettier -g'
            exit 1
        fi
        core:debugf 'check prettier end'

        for FILE in $STAGE_FILES
        do
            local type=$(pre-commit:filetype $FILE)
            core:debugf 'check file:'$FILE
            core:debugf 'file type:'$type
            pre-commit:lint:$type $FILE
      done

    else
        core:debugf 'no file need to be checked'
    fi

    exit 0
}

pre-commit:main $@
