#!/usr/bin/env bash

# rsync must be installed on the server

set -euxo pipefail

# Read deployment targets (unchanged)
user="$(<~/ctb-deploy.username)" || exit 1
sudoer_user="$(<~/ctb-deploy.sudoer-username)" || exit 1
server_user="$(<~/ctb-deploy.server-username)" || exit 1
server="$(<~/ctb-deploy.ip)" || exit 1
port="$(<~/ctb-deploy.port)" || exit 1

# Prompt once for the password without echoing it.
# Temporarily disable xtrace so the secret is not emitted.
set +x
# FIXME: Figure out how to turn off echoing.
printf "Password for %s@%s: " "$user" "$server" >&2
#stty -echo
IFS= read -r PASS
# || { stty echo; echo >&2; exit 1; }
#stty echo
echo >&2

printf "Password for %s@%s: " "$server_user" "$server" >&2
#stty -echo
IFS= read -r SERVER_USER_PASS
# || { stty echo; echo >&2; exit 1; }
#stty echo
echo >&2

printf "Password for %s@%s: " "$sudoer_user" "$server" >&2
#stty -echo
IFS= read -r SUDOER_USER_PASS
# || { stty echo; echo >&2; exit 1; }
#stty echo
echo >&2
set -x

cd ~/hc/ctoolbox || exit 1
version="$(cargo metadata --format-version=1 --no-deps | jq -r '.packages[] | select(.name == "ctoolbox") | .version')"
cd .. || exit 1
commit="$(git rev-parse HEAD)"
commitAndVersion="$version-$commit"

cd ~/ctb-vendored || exit 1
~/hc/scripts/vendor-dependencies

git archive HEAD -o "ctoolbox-dependencies-$commitAndVersion.zip"

#cp "ctoolbox-dependencies-$commitAndVersion.zip" ~/hc/assets/dependencies.zip

cd ~/hc || exit 1

./build linux-x64 --release

#rm ~/hc/assets/dependencies.zip || true

# Ensure sshpass is available to supply the password non-interactively.
if ! command -v sshpass >/dev/null 2>&1; then
	echo "sshpass is required but not installed. Please install sshpass or use SSH keys." >&2
	exit 1
fi

today="$(date +%Y%m%d_%H%M%S)"
mkdir -p ~/ctb-deploys/"$today" || exit 1
cp -r ~/hc/built/linux-x64/ctoolbox ~/ctb-deploys/"$today"/ctoolbox-"${commitAndVersion}" || exit 1
cp -r ~/"ctb-vendored/ctoolbox-dependencies-${commitAndVersion}.zip" ~/ctb-deploys/"$today"/ctoolbox-dependencies-"${commitAndVersion}".zip || exit 1

export SSHPASS="$PASS"

# Use sshpass with rsync and ssh so the password is reused.
SSHPASS="$PASS" sshpass -e rsync -e "ssh -p ${port}" -avz --chmod=0750 \
	~/hc/built/linux-x64/ctoolbox \
	"${user}@${server}:/home/${server_user}/deploy/ctoolbox-${commit}"

SSHPASS="$PASS" sshpass -e rsync -e "ssh -p ${port}" -avz \
	~/"ctb-vendored/ctoolbox-dependencies-${commitAndVersion}.zip" \
	"${user}@${server}:/home/${server_user}/deploy/ctoolbox-dependencies-${commit}.zip"

# Upload systemd unit file
SSHPASS="$PASS" sshpass -e rsync -e "ssh -p ${port}" -avz \
	~/hc/scripts/ctoolbox.service \
	"${user}@${server}:/home/${server_user}/.config/systemd/user/ctoolbox.service"

# Gracefully restart the service via ssh (using sshpass)
export SSHPASS="$SERVER_USER_PASS"
SSHPASS="$SERVER_USER_PASS" sshpass -e ssh -p "${port}" "${server_user}@${server}" bash -s "$commit" "$server_user" <<'REMOTE_SCRIPT'
commit="$1"
server_user="$2"
systemctl --user stop ctoolbox || true
# Wait for process to exit gracefully (timeout after 30s)
timeout 30 bash -c 'while systemctl --user is-active --quiet ctoolbox; do sleep 0.5; done' || true
REMOTE_SCRIPT

export SSHPASS="$PASS"
SSHPASS="$PASS" sshpass -e ssh -p "${port}" "${user}@${server}" bash -s "$commit" "$server_user" <<'REMOTE_SCRIPT'
commit="$1"
server_user="$2"

# Update symlink to new binary
ln -sfn "/home/$server_user/deploy/ctoolbox-$commit" "/home/$server_user/deploy/ctoolbox"
REMOTE_SCRIPT

export SSHPASS="$SUDOER_USER_PASS"
SSHPASS="$SUDOER_USER_PASS" sshpass -e ssh -p "${port}" "${sudoer_user}@${server}" bash -s "$server_user" <<'REMOTE_SCRIPT'
set -x
server_user="$1"

sudo bash -c 'echo setcap -r /home/"$0"/deploy/ctoolbox-*' "$server_user" || true
sudo bash -c 'setcap '\''cap_net_bind_service=+ep'\'' "$(readlink /home/"$0"/deploy/ctoolbox)"' "$server_user"
REMOTE_SCRIPT

export SSHPASS="$PASS"
SSHPASS="$PASS" sshpass -e ssh -p "${port}" "${user}@${server}" bash -s "$commit" "$server_user" <<'REMOTE_SCRIPT'
commit="$1"
server_user="$2"

cd /home/"$server_user"/deploy || exit 1
find . -maxdepth 1 -type f -name "ctoolbox-*" ! -name "ctoolbox-$commit" ! -name "ctoolbox-dependencies-$commit.zip" -exec rm {} \; || true
REMOTE_SCRIPT

export SSHPASS="$SERVER_USER_PASS"
SSHPASS="$SERVER_USER_PASS" sshpass -e ssh -p "${port}" "${server_user}@${server}" bash -s "$commit" "$server_user" <<'REMOTE_SCRIPT'
systemctl --user daemon-reload
# FIXME: Not sure if that's what's needed to make it start on reboot, but enable just says it's not found
#systemctl --user enable ctoolbox
systemctl --user start ctoolbox
systemctl --user status ctoolbox

sleep 60

systemctl --user status ctoolbox
REMOTE_SCRIPT

# Clear sensitive vars from the environment
unset PASS SSHPASS SERVER_USER_PASS