#!/usr/bin/env python3

"""Pause until a specific time."""

import sys
import time

sys.path.insert(0, '/usr/local/lib')

import modunits  # noqa ignore=E402


def usage(retval):
    """Output a usage message."""
    if retval in (0, None):
        write = sys.stdout.write
    else:
        write = sys.stderr.write

    write('Usage:\n')
    write('   {} hh:mm:ss\n'.format(sys.argv[0]))
    write('   {} hh:mm\n'.format(sys.argv[0]))
    write('   {} hh\n'.format(sys.argv[0]))

    sys.exit(retval)


def main():
    """Pause."""
    if len(sys.argv) != 2:
        sys.stderr.write('{}: must pass a single argument in argv\n'.format(sys.argv[0]))
        usage(1)

    if sys.argv[1] in ('-h', '--help'):
        usage(0)

    when_str = sys.argv[1]
    intended_fields = [int(x) for x in when_str.split(':')]
    while len(intended_fields) < 3:
        intended_fields.append(0)

    current_struct_time = time.localtime()
    current_fields = [current_struct_time.tm_hour, current_struct_time.tm_min, current_struct_time.tm_sec]

    intended_seconds = intended_fields[0] * 60 * 60 + intended_fields[1] * 60 + intended_fields[2]
    current_seconds = current_fields[0] * 60 * 60 + current_fields[1] * 60 + current_fields[2]

    if intended_seconds > current_seconds:
        # This is a time in the future.  Just add and sleep.
        adj_seconds = intended_seconds - current_seconds
    else:
        # This is a time in the past.  Increase the duration by one day, to make it in the future.
        # Note that this has problems with time changes, like jump ahead, fall back.
        print('That is a time in the past. Adding 24 hours to make it tomorrow.')
        adj_seconds = intended_seconds - current_seconds + 60 * 60 * 24

    adj_list = modunits.modunits(
            unitsvector='time',
            number=adj_seconds,
            detail='list',
            units='unabbreviated',
        )
    adj_list.reverse()
    adj_description = ', '.join(str(x) for x in adj_list)

    print('{} - Sleeping {} until {}'.format(time.ctime(), str(adj_description), time.ctime(time.time() + adj_seconds)))

    time.sleep(adj_seconds)
    print('{} - Time!'.format(time.ctime()))


main()