#!/usr/bin/env bash

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

create_bare_repository() {
    git init --bare "$2" > /dev/null
    PRERECEIVE_HOOK="$2/hooks/pre-receive"
    cat > "$PRERECEIVE_HOOK" <<EOF
#!/usr/bin/env bash
set -e; set -o pipefail;
cat | DOKKU_ROOT="$DOKKU_ROOT" dokku git-hook "$1"
EOF
    chmod +x "$PRERECEIVE_HOOK"
}

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

    # if we got here we have full access
    export NAME="dokku"
    export FINGERPRINT=""

    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-upload-pack)
    APP="$(echo $2 | perl -pe 's/(?<!\\)'\''//g' | sed 's/\\'\''/'\''/g')"
    pluginhook git-pre-pull $APP
    cat | git-upload-pack "$DOKKU_ROOT/$APP"
    pluginhook git-post-pull $APP
    ;;

  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
      [[ "$DOKKU_DISABLE_AUTO_APP_CREATE" == "1" ]] && fail "$APP: application doesn't exit, please create it with: dokku create $APP"
      create_bare_repository "$APP" "$APP_DIR"
    fi

    verify_app_name "$APP"

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

  create|apps:create)
    check_app_name "$2"
    verify_max_args 2 "$@"
    [[ -d "$APP_DIR/refs" ]] && fail "$APP: already exist"
    create_bare_repository "$APP" "$APP_DIR"
    info "Application $APP created!"
    ;;

  help | git:help)
    cat && cat <<EOF
    create <app>                 Create shallow app
EOF
    ;;

  *)
    exit $DOKKU_NOT_IMPLEMENTED_EXIT
    ;;

esac
