#!/bin/sh

ver_num=$(lsb_release -a 2>/dev/null | grep Release | awk  '{ print $2; }')
if (( $ver_num < 12 )) 
then
	BOOT_DIR="/boot"
else
	BOOT_DIR="/boot/firmware"
fi

git_repo="git://raspberrypi/root-ro.git"
svn_repo="http://raspberry49/svn/root-ro"

# Function to check Git repository availability
check_git_repo() {
	echo "Checking Git repository..."
	if git ls-remote "$1" &> /dev/null; then
		echo "Git repository is available."
		return 0
	else
		# echo "Git repository is not available."
		return 1
	fi
}

# Function to check SVN repository availability
check_svn_repo() {
	echo "Checking SVN repository..."
	if svn info "$1" &> /dev/null; then
		echo "SVN repository is available."
		return 0
	else
		echo "SVN repository is not available."
		return 1
	fi
}

initrd_path="${BOOT_DIR}/initrd.gz"
rm_initrd_path() {
	# check file 
	if [ -e "$initrd_path" ]; then
		# delete file
		rm -f  "$initrd_path"
		echo "File $initrd_path deleted."
	else
		echo "File $initrd_path not found."
	fi
}

sudo apt update
cd /home/pi

#git clone https://github.com/josepsanzcamp/root-ro.git
##svn co http://nas-27-59-fd/svn/root-ro   --non-interactive --no-auth-cache --username jin --password jin
# Check Git repository
if check_git_repo "$git_repo"; then
	echo "Downloading from Git repository..."
	git clone "$git_repo"
else
	# Check SVN repository if Git is not available
	if check_svn_repo "$svn_repo"; then
		echo "Downloading from SVN repository..."
		# svn checkout "$svn_repo"
		svn checkout "$svn_repo"   --non-interactive --no-auth-cache --username jin --password jin
	else
		echo "Both Git and SVN repositories are not available."
		exit 1
	fi
fi
#  svn co http://raspberry49/svn/root-ro   --non-interactive --no-auth-cache --username jin --password jin

# sudo bash
apt-get install -y git rsync gawk busybox bindfs subversion
dphys-swapfile swapoff
dphys-swapfile uninstall
update-rc.d dphys-swapfile disable
systemctl disable dphys-swapfile

rm_initrd_path
rsync -va root-ro/etc/initramfs-tools/* /etc/initramfs-tools/
mkinitramfs -o ${BOOT_DIR}/initrd.gz
echo initramfs initrd.gz >> ${BOOT_DIR}/config.txt
mkdir -p /media/netdir
# echo  192.168.1.220   nas-48-71-3b  >>  /etc/hotsa

reboot

