#!/usr/bin/python3 -sP
# GPL. (C) 2007-2009 Paolo Patruno.

# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
# 

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'autoradio.settings'
from django.conf import settings

from django.core import management
import autoradio.settings
import autoradio.autoradio_config
import sys, optparse, autoradio.daemon
from autoradio import  _version_


def initdb(cwd):
    p = optparse.OptionParser(usage="usage: %prog [options]",version="%prog "+_version_)
    p.add_option("--syncdb", action="store_true",dest="syncdb", help="initialize autoradio DB (default %default)", default=False)
    p.add_option("--changeuser", action="store_true",dest="changeuser", help="change user to the user in config file (default %default)", default=False)
    p.add_option("--purgeenclosure", action="store_true",dest="purgeenclosure", help="remove orphaned files from enclosure(default %default) see --realrun", default=False)
    p.add_option("--purgespot", action="store_true",dest="purgespot", help="remove orphaned files from spot (default %default) see --realrun", default=False)
    p.add_option("--purgejingle", action="store_true",dest="purgejingle", help="remove orphaned files from jingle (default %default) see --realrun", default=False)
    p.add_option("--realrun", action="store_true",dest="realrun", help="triggers the actual execution of the command that deletes the files without further confirmation (default %default)", default=False)
    (options, args) = p.parse_args()


    import django
    django.setup()

    from autoradio.programs.models import Enclosure
    from autoradio.spots.models import Spot
    from autoradio.spots.models import Filler
    from autoradio.jingles.models import Jingle
    
    if (not options.syncdb and not options.purgeenclosure and not options.purgespot and not options.purgejingle):
        p.print_help()


    if (options.changeuser):
        dae=autoradio.daemon.Daemon()
        dae.switchuser(user=autoradio.autoradio_config.user,group=autoradio.autoradio_config.group,env=None)
        #os.chdir(cwd)

    if (options.syncdb):
        #management.call_command("migrate",no_initial_data=True )
        management.call_command("migrate" )

    if (options.purgeenclosure):
        import os
        dir=autoradio.settings.MEDIA_ROOT+"podcasts/episodes/files/"
        nremoved=0
        files = os.listdir(dir)
        for file in files:
            file=dir+file
            #print ("cerca:",file)
            found = False
            for enclosure in Enclosure.objects.all():
                #print(enclosure.file.path)
                if file==enclosure.file.path:
                    found=True
            #print("found", found)
            if not found:
                print ("remove: ",file)
                nremoved+=1
                if options.realrun: os.remove(file)
            else:
                print ("OK    : ",file)
        print("orphaned files:",nremoved)

        for enclosure in Enclosure.objects.all():
            if (not os.path.exists(enclosure.file.path)):
                print ("error enclosure missed file:", enclosure, enclosure.file.path)

    if (options.purgespot):
        import os
        dir=autoradio.settings.MEDIA_ROOT+"spots/"
        nremoved=0
        files = os.listdir(dir)
        for file in files:
            file=dir+file
            #print ("cerca:",file)
            found = False
            for spot in Spot.objects.all():
                #print(spot.file.path)
                if file==spot.file.path:
                    found=True
            for filler in Filler.objects.all():
                #print(filler.file.path)
                if file==filler.file.path:
                    found=True
            #print("found", found)
            if not found:
                print ("remove: ",file)
                nremoved+=1
                if options.realrun: os.remove(file)
            else:
                print ("OK    : ",file)
        print("orphaned files:",nremoved)

        for spot in Spot.objects.all():
            if (not os.path.exists(spot.file.path)):
                print ("error spot missed file:", spot, spot.file.path)

        for filler in Filler.objects.all():
            if (not os.path.exists(filler.file.path)):
                print ("error filler missed file:", filler, filler.file.path)
        
    if (options.purgejingle):
        import os
        dir=autoradio.settings.MEDIA_ROOT+"jingles/"
        nremoved=0
        files = os.listdir(dir)
        for file in files:
            file=dir+file
            #print ("cerca:",file)
            found = False
            for jingle in Jingle.objects.all():
                #print(jingle.file.path)
                if file==jingle.file.path:
                    found=True
            #print("found", found)
            if not found:
                print ("remove: ",file)
                nremoved+=1
                if options.realrun: os.remove(file)
            else:
                print ("OK    : ",file)
        print("orphaned files:",nremoved)

        for jingle in Jingle.objects.all():
            if (not os.path.exists(jingle.file.path)):
                print ("error jingle missed file:", jingle, jingle.file.path)
        
if __name__ == '__main__':

    cwd=os.getcwd()

    sys.exit(initdb(cwd))  # (this code was run as script)
