#!/usr/bin/python3
# hook that runs ntpdate before duplicity to sync clock to UTC

import os
import sys
import subprocess
from string import Template

NTPSERVER = os.environ.get("NTPSERVER", "2.pool.ntp.org")

ERROR_TPL = """\
##########################
## FIXCLOCK HOOK FAILED ##
##########################

Amazon S3 and Duplicity need a UTC synchronized clock so we invoked the
following command::

    $COMMAND

You can change the NTP server like this:

    export NTPSERVER=my.ntp-server.net
    tklbam-backup

Unfortunately, something went wrong...

$ERROR

"""

def fixclock():
    os.environ['PATH'] += ':/usr/sbin'

    command = ["ntpdate", "-u", NTPSERVER]

    p = subprocess.run(command, capture_output=True, text=True)
    if p.returncode != 0:
        msg = Template(ERROR_TPL).substitute(COMMAND=' '.join(command),
                                             ERROR=p.stderr)

        print(msg, end=' ', file=sys.stderr)
        sys.exit(1)

def main():
    op, state = sys.argv[1:]

    if op in ('restore', 'backup') and state == 'pre':
        fixclock()

if __name__ == "__main__":
    main()
