#!/bin/bash

# IMPORTANT: always use relative paths, as tests move the folders to temp dirs
base_path="/tmp/impacted/"
origin_path="repo_origin"
source_path="source_repo"
new_clone_path="new_clone"
no_remote_path="no_remote"
ghub_actions_path="ghub_actions_clone"

base_branch="master"
feature_branch="feature"

mkdir -p $base_path
cd $base_path

# create origin
mkdir -p $origin_path
cd $origin_path && git init --bare
cd ..

# create git repo
mkdir -p $source_path && cd $source_path
git init && git remote add origin "../$origin_path"
echo "Hello, world!" >>README.md && git add README.md && git commit -m "Initial commit"
echo "Hello, world!" >>README.md && git add README.md && git commit -m "Update README"
git push origin master
base_commit=$(git rev-parse HEAD)
# create feature branch
git checkout -b $feature_branch
echo "Feature branch change" >>README.md && git add README.md && git commit -m "Feature branch commit"
git push origin $feature_branch
cd ..

# clone with remote branch cloned into master branch of local repo
mkdir -p $new_clone_path && cd $new_clone_path
git init
git remote add origin "../$origin_path"
git fetch origin $feature_branch
git reset --hard "origin/$feature_branch"
cd ..

# remote pointing to non existing repo
mkdir -p $no_remote_path && cd $no_remote_path
git init
echo "base branch file" >>README.md && git add README.md && git commit -m "first commit"
git remote add origin "git@git.com:datadog/non_existing_repo.git"
cd ..

# github actions style clone
mkdir -p $ghub_actions_path && cd $ghub_actions_path
git init
git remote add origin "../$origin_path"
git fetch --no-tags --prune --no-recurse-submodules origin $feature_branch
git checkout --progress --force -B $feature_branch "refs/remotes/origin/$feature_branch"
cd ..

echo "BASE COMMIT: $base_commit"

# cleanup
(cd $origin_path && rm -rf hooks info logs COMMIT_EDITMSG description index README.md)
(cd $source_path && rm -rf .git/hooks .git/info .git/logs .git/COMMIT_EDITMSG .git/description .git/index README.md && mv .git git)
(cd $new_clone_path && rm -rf .git/hooks .git/info .git/logs .git/COMMIT_EDITMSG .git/description .git/index README.md && mv .git git)
(cd $no_remote_path && rm -rf .git/hooks .git/info .git/logs .git/COMMIT_EDITMSG .git/description .git/index README.md && mv .git git)
(cd $ghub_actions_path && rm -rf .git/hooks .git/info .git/logs .git/COMMIT_EDITMSG .git/description .git/index README.md && mv .git git)
