#!/usr/bin/env python
# -*- coding: utf-8 -*-
# +--------------------------------------------------------------------------+
# | Endian Firewall                                                          |
# +--------------------------------------------------------------------------+
# | Copyright (c) 2016 S.p.A. <info@endian.com>                              |
# |         Endian S.p.A.                                                    |
# |         via Pillhof 47                                                   |
# |         39057 Appiano (BZ)                                               |
# |         Italy                                                            |
# |                                                                          |
# | 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 2 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, write to the Free Software Foundation, Inc.,  |
# | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.              |
# +--------------------------------------------------------------------------+

import tarfile
import grp
import os
import sys


def fix_nobody_group(tarfilename):
    try:
        groupinfo = grp.getgrnam('nogroup')
    except KeyError:
        # No groupname nogroup on this machine
        return
    t = tarfile.open(tarfilename)
    for x in t.getmembers():
        if x.gname == 'nobody' and os.path.exists("/" + x.path):
            os.chown("/" + x.path, -1, groupinfo.gr_gid)


def main():
    tarfilename = sys.argv[1]
    if not os.path.exists(tarfilename):
        print "Cannot open %s, no such file" % tarfilename
        return
    fix_nobody_group(tarfilename)

if __name__ == '__main__':
    main()
