| 1 | #!/bin/sh |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | set -eu |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | test ! -c /dev/rtc0 || exit 0 |
| 12 | |
| 13 | |
| 14 | command -v systemctl >/dev/null 2>&1 || exit 0 |
| 15 | |
| 16 | echo_with_time_usec() { |
| 17 | time_usec=$(timedatectl show --property=TimeUSec) |
| 18 | echo "${time_usec}, ${1}" |
| 19 | } |
| 20 | |
| 21 | |
| 22 | max_retry=60 retry=0 |
| 23 | until ntp_synchronized=$(timedatectl show --property=NTPSynchronized --value) && [ "${ntp_synchronized}" = "yes" ] || |
| 24 | [ "${retry}" -gt "${max_retry}" ]; do |
| 25 | if [ "${retry}" -eq 0 ]; then |
| 26 | |
| 27 | |
| 28 | |
| 29 | reference_file="${LIMA_CIDATA_MNT:-/mnt/lima-cidata}/user-data" |
| 30 | [ -f "${reference_file}" ] || reference_file="${0}" |
| 31 | |
| 32 | |
| 33 | echo_with_time_usec "Setting the system time to the modification time of ${reference_file}." |
| 34 | |
| 35 | |
| 36 | systemctl stop systemd-timesyncd |
| 37 | |
| 38 | |
| 39 | |
| 40 | until pid_of_timesyncd=$(systemctl show systemd-timesyncd --property=MainPID --value) && [ "${pid_of_timesyncd}" -eq 0 ]; do |
| 41 | echo_with_time_usec "Waiting for systemd-timesyncd to stop..." |
| 42 | sleep 1 |
| 43 | done |
| 44 | |
| 45 | |
| 46 | modification_time=$(stat -c %y "${reference_file}") |
| 47 | echo_with_time_usec "Setting the system time to ${modification_time}." |
| 48 | timedatectl set-time "${modification_time}" |
| 49 | |
| 50 | |
| 51 | systemctl start systemd-timesyncd |
| 52 | else |
| 53 | echo_with_time_usec "Waiting for NTP synchronization..." |
| 54 | fi |
| 55 | retry=$((retry + 1)) |
| 56 | sleep 1 |
| 57 | done |
| 58 | |
| 59 | ntp_message=$(timedatectl show-timesync --property=NTPMessage) |
| 60 | if [ "${ntp_synchronized}" = "yes" ]; then |
| 61 | echo_with_time_usec "NTP synchronization complete." |
| 62 | echo "${ntp_message}" |
| 63 | else |
| 64 | echo_with_time_usec "NTP synchronization timed out." |
| 65 | echo "${ntp_message}" |
| 66 | exit 1 |
| 67 | fi |