#!/usr/bin/env bash
set -euo pipefail

if [[ "$#" != "2" ]]; then
  echo "Usage: apply-update.sh SOURCE VERSION" >&2
  exit 2
fi

source_file="$1"
expected_version="$2"
target_dir="/opt/fsrdp-client"
target_file="$target_dir/FsRdpClient"
temporary_file="$target_dir/FsRdpClient.new"

if [[ ! "$expected_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "Invalid update version." >&2
  exit 3
fi
if [[ ! -f "$source_file" || -L "$source_file" || ! -x "$source_file" ]]; then
  echo "Invalid update executable." >&2
  exit 4
fi

file_size="$(stat -c %s -- "$source_file")"
if (( file_size < 1048576 || file_size > 209715200 )); then
  echo "Invalid update executable size." >&2
  exit 5
fi
elf_magic="$(od -An -t x1 -N4 -- "$source_file" | tr -d ' \n')"
if [[ "$elf_magic" != "7f454c46" ]]; then
  echo "The update is not a Linux executable." >&2
  exit 6
fi

install -d -m 0755 "$target_dir"
install -m 0755 "$source_file" "$temporary_file"
chown root:root "$temporary_file"
mv -f -- "$temporary_file" "$target_file"

echo "FSRdpClient $expected_version installed."
