#!/usr/bin/env python3
#
# Copyright 2016 Nathan Sommer and Ben Coleman
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
git hook script that is run when a student pushes to an assignment repository.

This file should be placed here:
~<student>/<faculty>/<class>/<assignment>.git/hooks/post-receive

It must be executable.

When it is run, a line like this is appended to the student's log:

<timestamp> SUBMISSION <repo path> <commit hash>
"""

import getpass
import os
import fileinput

from gkeepcore.log_file import log_append_command
from gkeepcore.path_utils import log_path_from_username
from gkeepcore.shell_command import run_command


def main():
    log_path = log_path_from_username(getpass.getuser())

    # hash and reference information comes from stdin
    for line in fileinput.input():
        # each line is of the form "<old hash> <new hash> <ref name>"
        split_fields = line.split()
        new_hash = split_fields[1]

        payload = '{} {}'.format(os.getcwd(), new_hash)

        command = log_append_command(log_path, 'SUBMISSION', payload)
        run_command(command)


if __name__ == '__main__':
    main()
