#!/bin/bash
exec 2> >(tee -a /mnt/c/Users/human/Downloads/github-migrate-error-log.txt)

echo "Migrating repos from file list!"
if [ -f /mnt/c/Users/human/Downloads/github-migrate-error-log.txt ]; then
    echo -e "\t error log found, deleting"
    rm -f /mnt/c/Users/human/Downloads/github-migrate-error-log.txt
fi

while IFS= read -r repo; do
    local_repo="/mnt/c/Users/human/OneDrive/Documents/Git/${repo}"
    remote_repo="git-gitea:PrincessPi/${repo}.git"
    remote_repo_page="https://github.com/PrincessPi3/${repo}"

    echo -e "\nMigrating repo at $local_repo from $remote_repo_page to $remote_repo"

    if [ ! -d $local_repo ]; then
        echo -e "\tFAIL! $local_repo not found! carrying on to next one" >&2
        continue
    fi

    if [ ! -d $local_repo/.git ]; then
        echo -e "\tNo .git found, initing it"
        git init
    fi

    echo -e "\ttrying creating remote repo..."
    if ! tea-cli repos create --init --name $repo --login WSL; then
         echo -e "\t\t$repo already exists on gitea! not skipping!"
         # continue
    fi

    echo -e "\tchagging dir to $local_repo"
    cd "$local_repo"

    echo -e "\ttrying git status..."
    if ! git status; then
        echo -e "\t\tstatus messy: trying git pull..."
        if ! git pull; then
            echo -e "\t\t\tforcably syncing with old remote, preferring local..."
            echo -e "\t\t\t\tgit adding..."
            git add .
            echo -e "\t\t\t\tgit comitting..."
            git commit -m "rebase from local"
            echo -e "\t\t\t\t git force pushing"
            git push -f
       fi
    fi

    echo -e "\ttrying setting remote origin..."
    if ! git remote set-url origin $remote_repo; then
        echo -e "\t\tadding remote origin..."
        git remote add origin $remote_repo
    fi

    echo -e "\tcreating empty file migration.tmp"
    touch migration.tmp

    echo -e "\tgit adding and git comitting"
    git add .
    git commit -m "migration"

    echo -e "\tTrying pushing (origin main...)"
    if ! git push -u origin main -f; then
        echo -e "\t\tTrying push (origin master)..."
        git push -u origin master -f
    fi
done < /mnt/c/Users/human/Downloads/repos-from-github.txt
