#!/bin/bash
#
# Owned by RunCloud
# Usage without permission is prohibited

ACTION=$1
GIT=$2
TARGET=$3
BRANCH=$4
GITUSER=$5
KEY=${GITUSER}_rsa
HOSTSERVER=`echo $GIT | cut -f2 -d @ | cut -f1 -d :`
SSHHELPERPATH=$6

function removeOldGithubKey {
    # fix to remove old github public key https://github.blog/2023-03-23-we-updated-our-rsa-ssh-host-key/
    REMOVE_TARGETHOST="github.com"
    REMOVE_KEY="AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ=="

    # Check if the key exists in the known_hosts file and if it matches the given key
    if ssh-keygen -F $REMOVE_TARGETHOST | grep "$REMOVE_KEY" >/dev/null; then
        ssh-keygen -R $REMOVE_TARGETHOST
    fi
}

removeOldGithubKey

function removeOldBitbucketKey {
    # fix to remove old bitbucket public key https://bitbucket.org/blog/ssh-host-key-changes
    REMOVE_TARGETHOST="bitbucket.org"
    REMOVE_KEY="AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl"

    # Check if the key exists in the known_hosts file and if it matches the given key
    if ssh-keygen -F $REMOVE_TARGETHOST | grep "$REMOVE_KEY" >/dev/null; then
        ssh-keygen -R $REMOVE_TARGETHOST && sed -i.old -e '/AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/d' ~/.ssh/known_hosts && curl https://bitbucket.org/site/ssh >> ~/.ssh/known_hosts
    fi
}

removeOldBitbucketKey

if [ ! -n "$(grep "^$HOSTSERVER " ~/.ssh/known_hosts)" ]; then ssh-keyscan $HOSTSERVER >> ~/.ssh/known_hosts 2>/dev/null; fi

echo "#!/bin/bash
ssh -o PreferredAuthentications=publickey -i /opt/RunCloud/.ssh/$KEY \"\$@\"" > $SSHHELPERPATH
chmod +x $SSHHELPERPATH

export GIT_SSH="$SSHHELPERPATH"

function sshKeyExists {
    cmd=`ls /opt/RunCloud/.ssh 2> /dev/null | grep $KEY`

    if [[ $? -eq 0 ]]; then
        return 0
    fi

    return 1
}

function sshConfigExists {
    cmd=`grep $KEY ~/.ssh/config 1>/dev/null 2>/dev/null`

    if [[ $? -eq 0 ]]; then
        return 0
    fi

    return 1
}

function isGitDir {
    if git rev-parse --git-dir > /dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}




if  ! sshKeyExists; then
    exit 3
fi

# if ! sshConfigExists; then
#     exit 4
# fi

cd $TARGET &> /dev/null

if [[ $? != 0 ]]; then
    mkdir -p $TARGET
fi



if [[ $ACTION == 'clone' ]]; then
    if ! isGitDir; then
        git clone --depth 1 --no-single-branch $GIT $TARGET -b $BRANCH
        exit $?
    elif [[ $(git config --get remote.origin.url) != "$GIT" ]]; then
        exit 5
    else
        currentBranch=$(git rev-parse --abbrev-ref HEAD)
        if [ "$currentBranch" != "$BRANCH" ]; then
            echo "$BRANCH"
            git checkout $BRANCH
        fi

        git pull
        exit $?
    fi
elif [[ $ACTION == 'pull' ]]; then
    if  ! isGitDir; then
        exit 7
    fi
    
    if [[ $(git config --get remote.origin.url) != "$GIT" ]]; then
        exit 5
    else
        currentBranch=$(git rev-parse --abbrev-ref HEAD)
        if [ "$currentBranch" != "$BRANCH" ]; then
            echo "$BRANCH"
            git checkout $BRANCH
        fi

        OLDCOMMITRC=`git rev-parse HEAD`
        currentBranch=$(git rev-parse --abbrev-ref HEAD)
        git fetch
        ORIGINLATESTCOMMIT=`git rev-parse origin/$currentBranch`

        # kalau HEAD sama dgn origin, tak payah pull
        if [[ "$ORIGINLATESTCOMMIT" == "$OLDCOMMITRC" ]]; then
            exit 8
        fi

        git merge
        exit $?
    fi
elif [[ $ACTION == 'changebranch' ]]; then
    if [[ $(git config --get remote.origin.url) != "$GIT" ]]; then
        exit 5
    else
        currentBranch=$(git rev-parse --abbrev-ref HEAD)
        if [ "$currentBranch" != "$BRANCH" ]; then
            git fetch origin
            git checkout $BRANCH
            if [[ $? != 0 ]]; then
                exit 6
            fi
            exit 0
        fi
        exit 0
    fi
fi

