#!/usr/bin/env bash
# version 1.2.4
# Author: Steve Magnuson, AG7GN
#
# This script prepares the stock "Raspberry Pi OS with desktop" Bullseye image from 
# https://www.raspberrypi.org/software/operating-systems/ for use with the 
# Nexus DR-X hat and Fe-Pi audio hat.
#
# After installing the "Raspberry Pi OS with desktop" image, make sure the Pi has
# access to the Internet, then open Terminal and run this command:
#

GIT_URL="https://github.com"
LOCAL_GIT_REPO_ROOT="/usr/local/src/nexus"
NEXUS_AUDIO_GIT_URL="${GIT_URL}/NexusDR-X/nexus-audio.git"
NEXUS_UPDATE_GIT_URL="https://github.com/NexusDR-X/nexus-update"
NEXUS_UTILS_GIT_URL="https://github.com/NexusDR-X/nexus-utils"
NEXUS_BOOTSTRAP_GIT_URL="${GIT_URL}/NexusDR-X/nexus-bootstrap.git"
AUTOSTART="/etc/xdg/lxsession/LXDE-pi/autostart"
NEXUS_VERSION="20220101.5"


function Error () {
	echo >&2 ">>>> FAILED: $1"
	echo >&2 "Bootstrap 1 of 2 DID NOT complete!"
	exit 1
}

#function bootAndRunAgain () {
#	if [[ -s $AUTOSTART ]] 
#	then
#		sudo sed -i "/@pcmanfm .*/a @lxterminal -e 'bash <(curl -sL https:\/\/raw.githubusercontent.com\/node-red\/linux-installers\/master\/deb\/update-nodejs-and-nodered)'" $AUTOSTART
#	fi
#	shutdown -r now
#}

function CheckInternet() {
	# Check for Internet connectivity
	if ! ping -q -w 1 -c 1 github.com &>/dev/null
	then
		Error "No internet connection detected. Connect this Pi to the Internet and run this script again." 
	fi
}

#SCRIPT="$(basename $0)"
#AUTOSTART="/etc/xdg/lxsession/LXDE-pi/autostart"
#if [[ -s $AUTOSTART ]] 
#then
#	# Remove any existing reference to this script from $AUTOSTART
#	sudo sed -i "/@lxterminal .*$SCRIPT/d" $AUTOSTART
#fi

#######################################################################
## Expand the filesystem if it is < 10 GB 
#PARTSIZE=$( df | sed -n '/root/{s/  */ /gp}' | cut -d ' ' -f2 )
#THRESHOLD=$((10 * 1024 * 1024))
#if (( $PARTSIZE < $THRESHOLD ))
#then
#	echo >&2 "Expanding root filesystem..."
#	sudo raspi-config --expand-rootfs
#	echo >&2 "Done. Rebooting. This script will autostart and continue setup after bootup."
#	sleep 5
#	bootAndRunAgain
#fi

#######################################################################
## Change password
#echo >&2 "Changing password to 'changeme'..."
#echo 'pi:changeme' | sudo chpasswd
#echo >&2 "Done."

#######################################################################
## Determine OS
eval $(cat /etc/*-release)
if [[ ${VERSION_CODENAME^^} != "BULLSEYE" ]]
then
	echo >&2 -e "\033[1;33;41;5mERROR! ERROR! ERROR! \033[0m\033[1;33m This script will only run with RaspiOS \"Bullseye\" OS! \033[0m"
	echo >&2 -e "\n\033[1;33mPlease follow the directions in the Wiki at https://github.com/NexusDR-X/nexus-bootstrap/wiki \033[0m\n"
	exit 1
fi
OS_BITS=$(getconf LONG_BIT)
echo >&2 "------>  Found Bullseye ${OS_BITS}-bit Operating System"

#######################################################################
## Make the documentation and src directories.
echo >&2 "------>  Make various folders..."
sudo mkdir -p /usr/local/share/doc || Error "Could not create /usr/local/share/doc"
sudo mkdir -p /usr/local/share/applications || Error "Could not create /usr/local/share/applications"
sudo mkdir -p /usr/local/share/nexus || Error "Could not create /usr/local/share/nexus"
sudo chown $USER:$USER /usr/local/share/nexus || Error "Could not chown $USER:$USER /usr/local/share/nexus"
mkdir -p $HOME/.config/nexus || Error "Could not create $HOME/.config/nexus"
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Enable source packages
echo >&2 "------>  Enable sources..."
for F in /etc/apt/sources.list /etc/apt/sources.list.d/raspi.list
do
	sudo sed -i -e 's/^#deb-src/deb-src/' $F || Error "Could not enable sources"
done
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Enable Interfaces
for I in do_i2c do_serial do_ssh do_vnc
do
	echo >&2 "------>  Enable ${I##*_}..."
	sudo raspi-config nonint $I 0 || Error "Could not enable $I"
	echo >&2 -e "------>  Done.\n______"
done

#######################################################################
## Disable Screen Blanking
echo >&2 "------>  Disable screen blanking..."
sudo raspi-config nonint do_blanking 1 || Error "Could not disable screen blanking"
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Set VNC Resolution
echo >&2 "------>  Set VNC resolution..."
#sudo raspi-config nonint do_vnc_resolution "1280x720"
#sudo raspi-config nonint do_vnc_resolution "800x600"
sudo raspi-config nonint do_vnc_resolution "1920x1080" || Error "Could not set VNC resolution"
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Change terminal Settings
echo >&2 "------>  Configure lxterminal settings..."
CONFIG="$HOME/.config/lxterminal/lxterminal.conf"
FONT="Monospace 14"
SCROLLBACK=10000
GEOMETRY_COLUMNS=100
GEOMETRY_ROWS=30
sed -i -e "s/^fontname=.*/fontname=$FONT/" \
		-e "s/^scrollback=.*/scrollback=$SCROLLBACK/" \
		-e "s/^geometry_columns=.*/geometry_columns=$GEOMETRY_COLUMNS/" \
		-e "s/^geometry_rows=.*/geometry_rows=$GEOMETRY_ROWS/" "$CONFIG" || Error "Could not set lxterminal settings"
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Disable NFS Clients
echo >&2 -e "------>  Disable nfs-client..."
sudo systemctl disable nfs-client.target
echo >&2 -e "------>  Done.\n______"

#######################################################################
# Check Internet availability
echo >&2 "------>  Check for Internet access..."
CheckInternet
echo >&2 -e "------>  Done.\n______"

#######################################################################
##  Add nexusdr-x apt repo and prefer it over other repos
echo >&2 "------>  Add Nexus DR-X apt Repository..."
GITHUBIO_REPO_URL="https://nexusdr-x.github.io/bullseye-repo"
NEXUS_LIST="nexus.list"
KEY_PATH="/usr/share/keyrings/nexus-archive-keyring.gpg"
## 'apt-key add' has been deprecated
#curl -s --compressed "${GITHUBIO_REPO_URL}/KEY.gpg" | sudo apt-key add -
#sudo curl -s --compressed -o /etc/apt/sources.list.d/nexus.list #"${GITHUBIO_REPO_URL}/nexus.list"
# Here's the new way to add an apt repo and key:
curl -s --compressed "${GITHUBIO_REPO_URL}/KEY.gpg" | sudo gpg --dearmor | sudo tee ${KEY_PATH} 1>/dev/null || Error "Failed to get Nexus DR-X repo key"
curl -s -o /tmp/${NEXUS_LIST} ${GITHUBIO_REPO_URL}/${NEXUS_LIST} || Error "Failed to get Nexus DR-X repo URL"
sed -i -e "s|^deb |deb [signed-by=${KEY_PATH}] |" /tmp/${NEXUS_LIST}
sudo mv -f /tmp/${NEXUS_LIST} /etc/apt/sources.list.d/
cat > /tmp/99nexus << EOF
Package: *
Pin: origin nexusdr-x.github.io
Pin-Priority: 600
EOF
sudo mv -f /tmp/99nexus /etc/apt/preferences.d/
#sudo apt update
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Prepare for package updates
echo >&2 "------>  Update installed OS and packages..."
let T=60
echo >&2 "Checking if apt or apt-get is already running. Waiting up to $T seconds.."
while (( $T > 0 ))
do
 	[[ -z $(pgrep -x 'apt|apt-get') ]] && break
   sleep 1
   ((T--))
done
(( $T == 0 )) && Error "Could not update/install pacakges. Another apt is running." 
echo >&2 "OK to proceed with package updates and installs"
sudo apt-get -y --fix-broken install || Error "apt-get --fix-broken install failed"
sudo apt-get -y clean || Error "apt-get clean failed"
sudo apt-get update || Error "apt-get update failed"

#######################################################################
## Prompt for call sign and name for use in bootstrap1 script
sudo apt-get -y install yad
TITLE="Nexus DR-X Bootstrap part 1 of 2"
MSG_TEXT="<b>Minimal configuration of Fldigi, Flmsg, etc. calls
for your call sign and name. Provide them here if you like. If 
you don't provide them here, you'll be prompted again during 
part 2 of the bootstrap.</b>
"
MYCALL="N0CALL"
MYNAME="No One"
MSG=$(yad --center --borders=20 \
     	--title="$TITLE" --text-align=center \
     	--text="$MSG_TEXT" --form \
     	--field="Operator Callsign" "$MYCALL" \
     	--field="Operator Name" "$MYNAME" \
     	--buttons-layout=center \
    	--button="Cancel":1 --button="OK":0)
if [[ $? == 0 ]]
then
  	MYCALL="$(echo $MSG | awk 'BEGIN {FS="|" } { print $1 }')"
	MYNAME="$(echo $MSG | awk 'BEGIN {FS="|" } { print $2 }')"
fi
MYCALL="${MYCALL^^}"

#######################################################################
## Update installed packages
sudo apt-get -y autoremove || Error "apt-get autoremove failed"
sudo apt-get -y upgrade	|| Error "apt-get upgrade failed"
sudo apt-get -y dist-upgrade || Error "apt-get dist-upgrade failed"
sudo apt-get -y autoremove || Error "apt-get autoremove failed"
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Install additional packages
echo >&2 "------>  Install additional required packages for Nexus DR-X..."
sudo apt-get -y install vim tcpdump lsof gpm telnet minicom links exfatprogs \
		dosfstools dos2unix autoconf automake libtool cmake \
		extra-xdg-menus bc dnsutils libgtk-3-bin jq xdotool moreutils build-essential \
		aptitude hdparm watchdog gettext git imagemagick socat intltool libgtk-3-dev \
		autotools-dev || Error "Could not install additional packages"
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Immediately install libax25 because it requires a force install due
## to sharing a header file with libc6
echo>&2 "------> Force install libax25 due to conflict with libc6"
pushd . >/dev/null
cd $HOME
apt download libax25
popd >/dev/null
sudo dpkg -i --force-overwrite $HOME/libax25_*.deb || Error "Error installing libax25"
rm -f $HOME/libax25_*
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Firewall
echo >&2 "------>  Enable nftables firewall..."
sudo systemctl enable nftables.service
sudo systemctl start nftables.service
echo >&2 -e "------>  Done.\n______"
# Insert rule preventing multicast from egressing ax25 interfaces
echo >&2 -e "------>  Block multicast traffic out of ax interfaces..."
WHO="$USER"
WHEN="@reboot"
#WHAT="sudo /usr/sbin/nft add rule inet filter output oifname { ax0, ax1 } ip daddr { 224.0.0.22, 224.0.0.251, 239.255.255.250 } drop"
WHAT="sudo /usr/sbin/nft add rule inet filter output oifname { ax0, ax1 } ip daddr { 224.0.0.0/4 } drop"
JOB="$WHEN $WHAT"
cat <(fgrep -i -v "sudo /usr/sbin/nft add rule inet filter output oifname { ax0, ax1 }" <(sudo crontab -u $WHO -l)) <(echo "$JOB") | sudo crontab -u $WHO -
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Exclude Avahi traffic from ax interfaces
echo >&2 "------>  Exclude Avahi traffic from ax25 interfaces..."
sudo cp /etc/avahi/avahi-daemon.conf /etc/avahi/avahi-daemon.conf.original
sudo sed -i -e "s/^#deny-interfaces=.*/deny-interfaces=ax0,ax1/" /etc/avahi/avahi-daemon.conf || Error "Could not modify /etc/avahi/avahi-daemon.conf"
sudo systemctl restart avahi-daemon
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Move /tmp and /var/log to RAM
echo >&2 "------>  Move /tmp and /var/log to RAM..."
if ! grep -q -e "^tmpfs.*/tmp" /etc/fstab
then
	echo -e "tmpfs\t/tmp\ttmpfs\tdefaults,noatime,mode=1777,size=50m\t0\t0" | sudo tee --append /etc/fstab 1>/dev/null || Error "Error creating /tmp RAM disk"
fi
if ! grep -q -e "^tmpfs.*/var/log" /etc/fstab
then
	echo -e "tmpfs\t/var/log\ttmpfs\tdefaults,noatime,mode=0755,size=50m\t0\t0" | sudo tee --append /etc/fstab 1>/dev/null || Error "Error creating /var/log RAM disk"
fi
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Set default text editor (uncomment one of these)
echo >&2 "------>  Set default command line editor..."
#sudo update-alternatives --set editor /usr/bin/nano
sudo update-alternatives --set editor /usr/bin/vim.basic
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Enable hardware watchdog
echo >&2 "------>  Configure and enabling hardware watchdog timer..."
sudo cp -f /etc/watchdog.conf /etc/watchdog.conf.original
sudo sed -i -e "s/^#max-load-1[ \t].*/max-load-1 = 24/" \
				-e "s/^#max-load-5[ \t].*/max-load-5 = 18/" \
				-e "s/^#watchdog-device.*/watchdog-device = \/dev\/watchdog/" /etc/watchdog.conf || Error "Error enabling hardware watchdog"
if ! grep -q "^watchdog-timeout" /etc/watchdog.conf
then
	echo "watchdog-timeout = 15" | sudo tee --append /etc/watchdog.conf 1>/dev/null
fi
sudo systemctl enable watchdog
sudo systemctl start watchdog.service || Error "Error enabling hardware watchdog"
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Backup /boot/config.txt
echo >&2 "------>  Back up /boot/config.txt..."
sudo cp -f /boot/config.txt /boot/config.txt.original
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Enable HDMI monitor attachment anytime
echo >&2 "------>  Allow hotplug of HDMI monitor..."
sudo sed -i -e "s/^#hdmi_force_hotplug.*/hdmi_force_hotplug=1/" /boot/config.txt
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Add 'nocomposite' to KMS driver so that VNC will work (too slow otherwise)
## See: https://forums.raspberrypi.com/viewtopic.php?t=323294
#echo >&2 "------>  Add 'nocomposite' to DRM VC4 V3D KMS driver so VNC will work..."
#sudo sed -i -e "s/^dtoverlay=vc4-kms-v3d$/dtoverlay=vc4-kms-v3d,nocomposite/" /boot/config.txt
#echo >&2 -e "------>  Done.\n______"

#######################################################################
## Real Time Clock
echo >&2 "------>  Enable Real Time Clock module..."
if ! grep -q "^dtoverlay=i2c-rtc,ds3231" /boot/config.txt
then
	echo -e "# Enable ds3231 Real Time Clock (RTC)\ndtoverlay=i2c-rtc,ds3231"  | sudo tee --append /boot/config.txt 1>/dev/null || Error "Error enabling real time clock"
fi
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Disable the special key keyboard mapping tool
echo >&2 "------>  Disable special key keyboard mapping tool service..."
sudo update-rc.d -f triggerhappy remove
sudo systemctl disable triggerhappy.service
sudo systemctl disable triggerhappy.socket
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Prepare local git repository folder
echo >&2 "------>  Make local git repository root folder..."
sudo mkdir -p "$LOCAL_GIT_REPO_ROOT" || Error "Error creating $LOCAL_GIT_REPO_ROOT"
sudo chown $USER:$USER "$LOCAL_GIT_REPO_ROOT" || Error "Error running chown $USER:$USER $LOCAL_GIT_REPO_ROOT"
git config --global pull.rebase false
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Fe-Pi Audio Card and PulseAudio setup
echo >&2 "------>  Enable Fe-Pi Audio Hat..."
if ! grep -q "^dtoverlay=fe-pi-audio" /boot/config.txt
then
	echo -e "# Enable Fe-Pi audio card\ndtoverlay=fe-pi-audio"  | sudo tee --append /boot/config.txt 1>/dev/null
fi
echo >&2 -e "------>  Done.\n______"
echo >&2 "------>  Add nexus-audio repo (audio configuration for Fe-Pi Audio Hat)..."
rm -rf "$LOCAL_GIT_REPO_ROOT/nexus-audio"
git -C "$LOCAL_GIT_REPO_ROOT" clone "$NEXUS_AUDIO_GIT_URL"
pushd . >/dev/null
cd "$LOCAL_GIT_REPO_ROOT"
nexus-audio/nexus-install
popd >/dev/null
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Get the nexus-bootstrap repo
echo >&2 "------>  Add nexus-bootstrap repo..."
rm -rf "$LOCAL_GIT_REPO_ROOT/nexus-bootstrap"
git -C "$LOCAL_GIT_REPO_ROOT" clone "$NEXUS_BOOTSTRAP_GIT_URL" || Error "Error creating local bootstrap repo"
sudo cp -f $LOCAL_GIT_REPO_ROOT/nexus-bootstrap/bootstrap* /usr/local/sbin/
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Install Nexus utilities from github.com
for R in nexus-update nexus-utils direwolf-utils rigctl-utils
do
	echo >&2 "------>  Add $R repo..."
	rm -rf "$LOCAL_GIT_REPO_ROOT/$R"
	git -C "$LOCAL_GIT_REPO_ROOT" clone "https://github.com/NexusDR-X/$R" || Error "Error creating local nexus-utils repo"
	pushd . >/dev/null
	cd "$LOCAL_GIT_REPO_ROOT"
	${R}/nexus-install
	popd >/dev/null
	echo >&2 -e "------>  Done.\n______"
done

#######################################################################
## Get the nexus-update repo
#echo >&2 "------>  Add nexus-update repo..."
#rm -rf "$LOCAL_GIT_REPO_ROOT/nexus-update"
#git -C "$LOCAL_GIT_REPO_ROOT" clone "$NEXUS_UPDATE_GIT_URL"
#pushd . >/dev/null
#cd "$LOCAL_GIT_REPO_ROOT"
#nexus-update/nexus-install
#echo >&2 -e "------>  Done.\n______"

#######################################################################
## Get the nexus-utils repo
#echo >&2 "------>  Add nexus-utils repo..."
#rm -rf "$LOCAL_GIT_REPO_ROOT/nexus-utils"
#git -C "$LOCAL_GIT_REPO_ROOT" clone "$NEXUS_UTILS_GIT_URL"
#pushd . >/dev/null
#cd "$LOCAL_GIT_REPO_ROOT"
#nexus-utils/nexus-install
#echo >&2 -e "------>  Done.\n______"

#######################################################################
## Add cronjob to check for presence of DO_NOT_DELETE_THIS_FILE
echo >&2 "------>  Add cronjob to check for DO_NOT_DELETE_THIS_FILE file at startup..."
WHO="$USER"
WHEN="@reboot"
WHAT="sleep 5 && /usr/local/sbin/initialize-pi.sh"
JOB="$WHEN $WHAT"
cat <(fgrep -i -v "$WHAT" <(sudo crontab -u $WHO -l)) <(echo "$JOB") | sudo crontab -u $WHO -
echo "Initialized on $(date '+%Y-%m-%d %H:%M %Z')" > $HOME/DO_NOT_DELETE_THIS_FILE
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Shutdown button
echo >&2 "------>  Enable shutdown button..."
sudo cp -f ${LOCAL_GIT_REPO_ROOT}/nexus-bootstrap/etc/systemd/system/* /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable shutdown_button.service
sudo systemctl start shutdown_button.service
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Check piano switch at startup
# This is done by the nexus-utils/nexus-install script
#echo >&2 "------>  Add lxsession autostart task to check piano switch state at startup..."
#AUTOSTART="/etc/xdg/lxsession/LXDE-pi/autostart"
#if [[ -s $AUTOSTART ]] 
#then
#	if ! grep -q check-piano.sh $AUTOSTART 2>/dev/null
#	then
#		sudo sed -i '/@pcmanfm .*/a @bash \/usr\/local\/sbin\/check-piano.sh' $AUTOSTART
#	fi
#fi
#echo >&2 -e "------>  Done.\n______"

#######################################################################
## Desktop background
# This is done by the nexus-utils/nexus-install script
#echo >&2 "------>  Set desktop background..."
#cp ${LOCAL_GIT_REPO_ROOT}/nexus-bootstrap/Pictures/*.jpg $HOME/Pictures/
#mkdir -p $HOME/.config/pcmanfm/LXDE-pi
#cp ${LOCAL_GIT_REPO_ROOT}/nexus-bootstrap/config/pcmanfm/LXDE-pi/desktop-items-0.conf $HOME/.config/pcmanfm/LXDE-pi/
#sed -i -e "s|_HOME_|$HOME|" $HOME/.config/pcmanfm/LXDE-pi/desktop-items-0.conf
#pcmanfm --reconfigure
#echo >&2 -e "------>  Done.\n______"

#######################################################################
## Make .vimrc file
echo >&2 "------>  Install .vimrc file..."
if [[ ! -s $HOME/.vimrc ]]
then
	cp -f ${LOCAL_GIT_REPO_ROOT}/nexus-bootstrap/vimrc $HOME/.vimrc
fi
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Modify Log Management
echo >&2 "------>  Modify log management..."
sed -n "/#### RULES ####/q;p" /etc/rsyslog.conf > /tmp/rsyslog.conf
cat $LOCAL_GIT_REPO_ROOT/nexus-bootstrap/etc/rsyslog.conf.excerpt >> /tmp/rsyslog.conf 
sudo cp -f /etc/rsyslog.conf /etc/rsyslog.conf.backup
sudo cp -f /tmp/rsyslog.conf /etc/rsyslog.conf
sudo rm -f /var/log/debug*
sudo cp -f /etc/logrotate.conf /etc/logrotate.conf.backup
if grep -qE "^#compress" /etc/logrotate.conf
then
	sudo sed -i -e "s/^#compress.*/compress/" /etc/logrotate.conf
	sudo sed -i "/^compress/a compresscmd \/bin\/bzip2\nuncompresscmd \/bin\/bunzip2\ncompressoptions -9\ncompressext .bz2" /etc/logrotate.conf
fi

if ! grep -qf "$LOCAL_GIT_REPO_ROOT/nexus-bootstrap/etc/logrotate.d/rsyslog" /etc/logrotate.d/rsyslog
then
	sudo cp -f /etc/logrotate.d/rsyslog /etc/logrotate.d/rsyslog.backup
	cat "$LOCAL_GIT_REPO_ROOT/nexus-bootstrap/etc/logrotate.d/rsyslog" > /tmp/rsyslog
	cat /etc/logrotate.d/rsyslog >> /tmp/rsyslog
	sudo cp -f /tmp/rsyslog /etc/logrotate.d/rsyslog
	sudo systemctl restart rsyslog
fi
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Change hostname
echo >&2 "------>  Change hostname to nexuspi..."
sudo raspi-config nonint do_hostname "nexuspi"
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Generate a new VNC key
echo >&2 "------>  Generate new VNC server key..."
sudo vncserver-x11 -generatekeys force
sudo systemctl restart vncserver-x11-serviced
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Generate new SSH server keys
sudo rm -v /etc/ssh/ssh_host* 
echo >&2 "------>  Generate new SSH server key..."
#sudo dpkg-reconfigure -f noninteractive openssh-server
pushd . >/dev/null
sudo rm -f /etc/ssh/ssh_host_*
cd /etc/ssh
sudo ssh-keygen -A
sudo systemctl restart ssh >/dev/null 2>&1
echo "Remove ssh client keys, authorized_keys and known_hosts"
rm -f $HOME/.ssh/known_hosts
rm -f $HOME/.ssh/authorized_keys
rm -f $HOME/.ssh/id_*
rm -f $HOME/.ssh/*~
popd >/dev/null
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Set version (current date in YYYYMMDD format)
echo >&2 "------>  Set version..."
echo "NEXUS_VERSION=\"$NEXUS_VERSION RaspiOS ${VERSION_CODENAME^} ${OS_BITS}-bit\\n\\nBuilt $(date '+%Y-%m-%d %H:%M %Z')\"" | sudo tee /boot/nexus.txt 1>/dev/null
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Pause
echo >&2 "------>  Bootstrap 1 of 2 completed. Rebooting in 7 seconds, then bootstrap 2 of 2 will run..."
echo >&2 "------>  To ABORT the bootstrap process, press Ctrl-C. DO NOT do this unless instructed!"
echo >&2
sleep 7

#######################################################################
## Set autostart to launch nexus_os_bootstrap1 at next startup
echo >&2 "------>  Set autostart to launch bootstrap1 at next startup..."
#sudo sed -i "/@pcmanfm .*/a @lxterminal -e 'bash <(curl -sL https:\/\/nexusdr-x.github.io\/nexus-bootstrap\/nexus_os_bootstrap1)'" $AUTOSTART
sudo sed -i "/@pcmanfm .*/a @lxterminal -e /usr/local/sbin/bootstrap1 -f -c $MYCALL -n \"$MYNAME\"" $AUTOSTART
echo >&2 -e "------>  Done.\n______"

#######################################################################
## Reboot
shutdown -r now







