#!/usr/bin/env bash
# Commands such as git pull return exit code if there are no changes
# set -e

if [[ -n "$ADDONS_GIT_REPOS" ]]; then
    github_url="${GITHUB_URL:=https://github.com}"
    gitlab_url="${GITLAB_URL:=https://gitlab.com}"
    forgejo_url="${FORGEJO_URL:=https://codeberg.org}"
    local_path="${LOCAL_PATH:=/var/lib/odoo/git}"
    git_clone_depth="${GIT_CLONE_DEPTH:=999}"

    # Ensure configured URLs always have a protocol, so the comparison
    # ${git_proto}${git_hostname} = "$github_url" / "$gitlab_url" works
    # even when GITLAB_URL or GITHUB_URL is passed without one.
    # Defaults to https:// when missing.
    [[ "$github_url" =~ ^[a-zA-Z]+:// ]] || github_url="https://${github_url}"
    [[ "$gitlab_url"  =~ ^[a-zA-Z]+:// ]] || gitlab_url="https://${gitlab_url}"
    [[ "$forgejo_url" =~ ^[a-zA-Z]+:// ]] || forgejo_url="https://${gitlab_url}"

    # Setup git SSH key
    add-ssh-key

    # Make every git directory a safe directory
    git config --global --add safe.directory '*'

    # Clone git repo addons into local path
    log-entrypoint "Cloning git repos: $ADDONS_GIT_REPOS"
    addons_git_repos=$(echo "$ADDONS_GIT_REPOS" | tr ',' '\n')
    for addon_git_repo in $addons_git_repos; do

        # Supported urls:
        # addon_git_repo=git@github.com:OCA/server-tools
        # addon_git_repo=git@github.com:OCA/server-tools#16.0
        # addon_git_repo=https://github.com/OCA/server-tools#16.0
        # addon_git_repo=https://github.com/OCA/server-tools#18.0#8c5ea468176e8b960a0ae0a52128fc65e985e8a7

        git_url=$(echo "$addon_git_repo" | awk -F'#' '{print $1}')
        git_branch=$(echo "$addon_git_repo" | awk -F'#' '{print $2}')
        git_commit=$(echo "$addon_git_repo" | awk -F'#' '{print $3}')
        git_hostname=$(parse-url "$git_url" hostname)
        git_proto=$(parse-url "$git_url" proto)
        git_path=$(parse-url "$git_url" path | sed 's/.git//g')
        git_local_path="$local_path/${git_hostname}/$git_path"

        # Fallback git branch to Odoo version
        if [[ -z "$git_branch" ]]; then
            git_branch="$ODOO_VERSION"
        fi

        ssh_host_config=$(ssh -F "$HOME/.ssh/config" -G "$git_hostname" 2>/dev/null)
        ssh_hostname=$(echo "$ssh_host_config" | sed -n 's/^hostname //p')
        ssh_port=$(echo "$ssh_host_config" | sed -n 's/^port //p')
        ssh-keyscan -t rsa,ed25519 -p "${ssh_port:-22}" "${ssh_hostname:-$git_hostname}" > "$HOME/.ssh/known_hosts" 2>/dev/null

        if [[ ! -d "$git_local_path/.git" ]]; then

            # Clone git repo and submodules
            mkdir -p "$git_local_path"

            # Add GitHub personal access token
            if [[ "${git_proto}${git_hostname}" = "$github_url" ]] && [[ -n "$GITHUB_USERNAME" ]]; then
                git_url="${git_proto}${GITHUB_USERNAME}:${GITHUB_PAT}@${git_hostname}/${git_path}.git"
            fi

            # Add GitLab personal access token
            if [[ "${git_proto}${git_hostname}" = "$gitlab_url" ]] && [[ -n "$GITLAB_USERNAME" ]]; then
                git_url="${git_proto}${GITLAB_USERNAME}:${GITLAB_PAT}@${git_hostname}/${git_path}.git"
            fi

            # Add Forgejo personal access token
            if [[ "${git_proto}${git_hostname}" = "$forgejo_url" ]] && [[ -n "$FORGEJO_USERNAME" ]]; then
                git_url="${git_proto}${FORGEJO_USERNAME}:${FORGEJO_PAT}@${git_hostname}/${git_path}.git"
            fi

            log-entrypoint "Clone ${git_url} branch $git_branch."
            git clone --depth "$git_clone_depth" --single-branch --branch "$git_branch" "$git_url" "$git_local_path"
        else
            log-entrypoint "Pull $git_branch branch in $git_local_path."
            git -C "$git_local_path" switch "$git_branch"
            git -C "$git_local_path" pull
        fi

        if [[ -n "$git_commit" ]]; then
            log-entrypoint "Checkout $git_commit commit in $git_local_path."
            git -C "$git_local_path" checkout "$git_commit"
        fi

        if [[ -f "$git_local_path/.gitmodules" ]]; then
            log-entrypoint "Init and update git submodules in $git_local_path."
            git -C "$git_local_path" submodule update --init --recursive --depth "$git_clone_depth"
        fi
    done

    remove-ssh-key
fi
