#!/usr/bin/env python

# Copyright (C) 2011, Aleksey Lim
#
# 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/>.

import sys
import logging
import subprocess
from optparse import OptionParser
from ConfigParser import ConfigParser
from os.path import exists

sys.path.insert(0, '@SUGAR_SERVER_PYTHONPATH@')
from sugar_server import env, util, registry
from sugar_server.util import enforce


if len(sys.argv) == 1:
    print 'Usage: sugar-server-rsync [ROOT]'
    print
    print 'Restrictive wrapper around rsync to use specifically'
    print 'in .ssh/authorized_keys file on server side.'
    print
    exit(0)

config = ConfigParser()
config.read(__file__ + '.conf')

for prop in util.Option.items.values():
    if config.has_option(prop.section, prop.name):
        prop.value = config.get(prop.section, prop.name)

try:
    env.init(OptionParser(), 'backup-rsync')

    rsync = env.import_from('rsync', 'backup')
    trimmer = env.import_from('trimmer', 'backup')

    trimmer.logger = logging.getLogger()

    enforce(exists(rsync.RSYNC),
            'Cannot find %s program' % rsync.RSYNC)
    enforce(len(sys.argv) == 2, 'Only one argument is supported')

    uid = sys.argv[1]
    root = env.hashed_backup_path(uid)
    rsync_command, dry_run = rsync.cook_rsync_command(root)
    if rsync_command is None:
        exit(0)
    subprocess.check_call(rsync_command)
    registry.update('users', uid, pending_restore=False)
    if not dry_run:
        rsync.postprocess(root)
except Exception, error:
    logging.exception('Fail to process rsync request')
    exit(1)
