#!/usr/bin/env bash

source "$(dirname $0)/../dokku_common"

case "$1" in
  git-hook)
    verify_app_name "$2"

    while read oldrev newrev refname
    do
      # Only run this script for the master branch. You can remove this
      # if block if you wish to run it for others as well.
      if [[ $refname = "refs/heads/master" ]] ; then
        dokku rebuild "$APP" "$newrev"
      else
        echo $'\e[1G\e[K'"-----> WARNING: deploy did not complete, you must push to master."
        echo $'\e[1G\e[K'"-----> for example, try 'git push <dokku> ${refname/refs\/heads\/}:master'"
      fi

    done
    ;;

  git-*)
    APP="$(echo "$2" | perl -pe 's/(?<!\\)'\''//g' | sed 's/\\'\''/'\''/g')"
    check_app_name "$APP"

    if [[ $1 == "git-receive-pack" && ! -d "$APP_DIR/refs" ]]; then
        git init --bare $APP_DIR > /dev/null
        PRERECEIVE_HOOK="$APP_DIR/hooks/pre-receive"
        cat > "$PRERECEIVE_HOOK" <<EOF
#!/usr/bin/env bash
set -e; set -o pipefail;
cat | DOKKU_ROOT="$DOKKU_ROOT" dokku git-hook "$APP"
EOF
        chmod +x "$PRERECEIVE_HOOK"
    fi

    verify_app_name "$APP"

    args=$@
    git-shell -c "$args"
    ;;

  help)
    cat
    ;;
esac

