#!/usr/bin/env bash

# SPDX-FileCopyrightText: 2025 Romain Maneschi <romain@gitroot.dev>
#
# SPDX-License-Identifier: EUPL-1.2

trap 'catch $LINENO' ERR

EXPECTED_ERROR=0

catch() {
    if [[ $EXPECTED_ERROR == 0 ]]; then
        echo "🛑 unexpected error line $1"
        exit 1
    fi
    report "🟢 expected err line $1"
}

quiet_git() {
    echo "🚀 git $@" >> /tmp/mylog.txt
    GIT_TRACE=false GIT_TRACE_PACKET=false git "$@" &>> /tmp/mylog.txt
}

report() {
    echo "$1" >> /tmp/mylog.txt
    echo "$1"
}

mySleep() {
    echo "🕐 $1" >> /tmp/mylog.txt
    sleep $1
}

function wait_for() {
    start=`date +%s`
    timeout=100
    until [ $timeout -le 0 ] || (grep -q $1 $2 &> /dev/null); do
        sleep 0.1
        timeout=$(( timeout - 1 ))
    done
    if [ $timeout -le 0 ]; then
        return 1
    fi
    end=`date +%s`
    echo "🕐 $@ in `expr $end - $start` seconds"
}

function wait_ls() {
    start=`date +%s`
    timeout=100
    until [ $timeout -le 0 ] || [ $(ls $1 | wc -l) -eq $2 ]; do
        sleep 0.1
        timeout=$(( timeout - 1 ))
    done
    if [ $timeout -le 0 ]; then
        return 1
    fi
    end=`date +%s`
    echo "🕐 $@ in `expr $end - $start` seconds"
    mySleep 0.3
}

EXIT_CODE=0

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

SERVER_PORT="4545"
SERVER_URL=${1:-"127.0.0.1:$SERVER_PORT"}
SERVER_DATA_DIR="/tmp/gitrootData"

ROOT_REPO_NAME="root"
ROOT_REPO_URL="ssh://user@${SERVER_URL}/${ROOT_REPO_NAME}"

SSH_KEY="${SCRIPT_DIR}/user1/ed25519"
SSH_KEY2="${SCRIPT_DIR}/user2/ed25519"

LADYBUG_PROD_VERSION="https://gitroot.dev/releases/0.3.0/ladybug-0.0.3.wasm"
SILO_PROD_VERSION="https://gitroot.dev/releases/0.3.0/silo-0.0.3.wasm"
GRAFTER_PROD_VERSION="https://gitroot.dev/releases/0.3.0/grafter-0.0.3.wasm"
APEX_PROD_VERSION="https://gitroot.dev/releases/0.3.0/apex-0.0.3.wasm"
POLLEN_PROD_VERSION="https://gitroot.dev/releases/0.3.0/pollen-0.0.2.wasm"
HOP_PROD_VERSION="https://gitroot.dev/releases/0.3.0/hop-0.0.1.wasm"
ALL_PLUGINS_PROD_VERSION=( $LADYBUG_PROD_VERSION $SILO_PROD_VERSION $GRAFTER_PROD_VERSION $APEX_PROD_VERSION $POLLEN_PROD_VERSION $HOP_PROD_VERSION )

LADYBUG_WASM="${SCRIPT_DIR}/../plugins/ladybug/ladybug-0.0.4.wasm"
SILO_WASM="${SCRIPT_DIR}/../plugins/silo/silo-0.0.4.wasm"
GRAFTER_WASM="${SCRIPT_DIR}/../plugins/grafter/grafter-0.0.4.wasm"
APEX_WASM="${SCRIPT_DIR}/../plugins/apex/apex-0.0.4.wasm"
APEX_MARKDOWN_WASM="${SCRIPT_DIR}/../plugins/apex/apex_markdown-0.0.4.wasm"
APEX_CODE_WASM="${SCRIPT_DIR}/../plugins/apex/apex_code-0.0.4.wasm"
APEX_MERMAID_WASM="${SCRIPT_DIR}/../plugins/apex_mermaid/apex_mermaid-0.0.1.wasm"
POLLEN_WASM="${SCRIPT_DIR}/../plugins/pollen/pollen-0.0.3.wasm"
HOP_WASM="${SCRIPT_DIR}/../plugins/hop/hop-0.0.2.wasm"
STIGMA_WASM="${SCRIPT_DIR}/../plugins/stigma/stigma-0.0.1.wasm"

##### clean
report "🏁 clean"

cd /tmp
CACHE=${SERVER_DATA_DIR}/data/cache/
if [ -d "$CACHE" ]; then
    chmod -R +w "$CACHE"
fi
rm -rf ${SERVER_DATA_DIR}
rm -rf ${ROOT_REPO_NAME}
rm -f /tmp/mylog.txt
APP=$(lsof -i tcp:${SERVER_PORT} | awk 'NR!=1 {print $2}') 
if [ -z "$APP" ]; then
    report "🟢 Gitroot not launched"
else 
    kill ${APP}
    report "🟢 Gitroot killed"
fi
ssh-keygen -f "$HOME/.ssh/known_hosts" -R "[127.0.0.1]:$SERVER_PORT"

##### launch gitroot
report "🏁 launch gitroot from gitroot.dev"

if [ ! -f "/tmp/testUpdate/gitroot" ]; then
    mkdir /tmp/testUpdate
    cd /tmp/testUpdate

    wget -O gitroot https://gitroot.dev/releases/gitroot-last && chmod +x gitroot && ./gitroot --initConfig ./conf.yml

    for value in "${ALL_PLUGINS_PROD_VERSION[@]}"
    do
        wget $value
    done
fi

/tmp/testUpdate/gitroot --config /tmp/testUpdate/conf.yml -data="${SERVER_DATA_DIR}" &>> /tmp/mylog.txt &
wait_for "starting SSH server on" /tmp/mylog.txt

mySleep 1

##### first clone
report "🏁 first clone"

cd /tmp
quiet_git clone --quiet -c "core.sshCommand=ssh -i ${SSH_KEY} -o IdentitiesOnly=yes -o StrictHostKeyChecking=accept-new" ${ROOT_REPO_URL}
cd ${ROOT_REPO_NAME}
quiet_git remote add upstream ssh://gitroot.dev/
.gitroot/init.sh --pubKey "${SSH_KEY}.pub" --privKey "${SSH_KEY}" --email admin@gitroot.dev --name admin >> /tmp/mylog.txt
sed -i -e 's/- main/- dev/g' .gitroot/repoConfiguration.yml
quiet_git add .
quiet_git commit -m "my init"
quiet_git push origin main
quiet_git pull --rebase -X theirs upstream main
quiet_git push -f origin main
quiet_git remote remove upstream

##### kill last gitroot
report "🏁 kill last gitroot"
APP=$(lsof -i tcp:${SERVER_PORT} | awk 'NR!=1 {print $2}') 
if [ -z "$APP" ]; then
    report "🟢 Gitroot not launched"
else 
    kill ${APP}
    report "🟢 Gitroot killed"
fi
rm -f /tmp/mylog.txt

##### launch next gitroot
report "🏁 launch next gitroot"

cd ${SCRIPT_DIR}/../server
GIT_TRACE_PACKET=false go run -race . --config /tmp/testUpdate/conf.yml -data="${SERVER_DATA_DIR}" &>> /tmp/mylog.txt &
wait_for "starting SSH server on" /tmp/mylog.txt

cd /tmp/root
quiet_git pull origin main

sed -i "s|${LADYBUG_PROD_VERSION}|file://${LADYBUG_WASM}|g" .gitroot/plugins.yml
sed -i "s|${SILO_PROD_VERSION}|file://${SILO_WASM}|g" .gitroot/plugins.yml
sed -i "s|${GRAFTER_PROD_VERSION}|file://${GRAFTER_WASM}|g" .gitroot/plugins.yml
sed -i "s|${APEX_PROD_VERSION}|file://${APEX_WASM}|g" .gitroot/plugins.yml
sed -i "s|${POLLEN_PROD_VERSION}|file://${POLLEN_WASM}|g" .gitroot/plugins.yml
sed -i "s|${HOP_PROD_VERSION}|file://${HOP_WASM}|g" .gitroot/plugins.yml
echo "- url: '${APEX_CODE_WASM}'" >> .gitroot/plugins.yml
echo "  active: true" >> .gitroot/plugins.yml
echo "- url: '${APEX_MARKDOWN_WASM}'" >> .gitroot/plugins.yml
echo "  active: true" >> .gitroot/plugins.yml
echo "- url: '${APEX_MERMAID_WASM}'" >> .gitroot/plugins.yml
echo "  active: true" >> .gitroot/plugins.yml
echo "- url: '${STIGMA_WASM}'" >> .gitroot/plugins.yml
echo "  active: true" >> .gitroot/plugins.yml
echo "- url: '${HOP_WASM}'" >> .gitroot/plugins.yml
echo "  active: true" >> .gitroot/plugins.yml

sed -i 's|checksum: sha256:[a-f0-9]*|checksum: ""|g' .gitroot/plugins.yml

sed -i '/bwrap:/,/enabled:/ s/enabled: false/enabled: true/' .gitroot/forgeConfig.yml

quiet_git add .
quiet_git commit -m "update plugins"
quiet_git push origin main

mySleep 35

quiet_git pull origin main

##### kill gitroot
report "🏁 kill current gitroot"
APP=$(lsof -i tcp:${SERVER_PORT} | awk 'NR!=1 {print $2}') 
if [ -z "$APP" ]; then
    report "🟢 Gitroot not launched"
else 
    kill ${APP}
    report "🟢 Gitroot killed"
fi
rm -f /tmp/mylog.txt

cd ${SCRIPT_DIR}/../server
GIT_TRACE_PACKET=false go run -race . --config /tmp/testUpdate/conf.yml -data="${SERVER_DATA_DIR}" &>> /tmp/mylog.txt &
wait_for "starting SSH server on" /tmp/mylog.txt

cd /tmp/root
quiet_git pull origin main

rm .gitroot/plugins.yml
cp ${SCRIPT_DIR}/update-ressources/plugins.yml .gitroot/
quiet_git add .
quiet_git commit -m "update plugins 2"
rm makefile
cp ${SCRIPT_DIR}/update-ressources/makefile .
quiet_git add .
quiet_git commit -m "makefile"
cp -r ${SCRIPT_DIR}/../../plugins .
cp -r ${SCRIPT_DIR}/update-ressources/layout.html app/plugins/
cp -r ${SCRIPT_DIR}/../plugins app
quiet_git add .
quiet_git commit -m "makefile and plugins"
quiet_git push origin main
