#!/usr/bin/python

# nuke-ipod -- completely empty an ipod and create a new empty db on it

# Copyright 2008 Peter Maydell <pmaydell@chiark.greenend.org.uk>
#
#    nuke-ipod 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.
#
#    nuke-ipod 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/>.
#
# iTunes, iPod and Shuffle are trademarks of Apple.
# This product is not supported/written/published by Apple!

import gpod
import optparse
import os
import os.path
import shutil

def delete_directory_tree(top):
    # Remove an entire directory tree but don't
    # try to delete the top level directory itself.
    # (The latter requirement is why we can't just use
    # shutil.rmtree directly)
    for name in os.listdir(top):
        fullname = os.path.join(top, name)
        if os.path.isdir(fullname):
            delete_directory_tree(fullname)
            os.rmdir(fullname)
        else:
            os.remove(fullname)

def main():
    oparser = optparse.OptionParser(usage = 'usage: nuke-ipod [options] ipoddir')
    oparser.add_option('--really',
                       dest='really',
                       default=False,
                       action='store_true',
                       help='Really delete everything on the ipod')
    opts,args = oparser.parse_args()
    if len(args) > 1:
        oparser.error("Too many arguments")
    elif len(args) == 0:
        oparser.error("ipod mount point not specified")
    mount = args[0]

    if not opts.really:
        print "nuke-ipod will delete everything on the ipod mounted at %s" % mount
        print "WARNING: no check is made that it is actually an ipod!"
        print "If you really want to do this then use the --really option"
        return

    print "Deleting contents of ipod..."
    delete_directory_tree(mount)
    print "Creating fresh database..."
    gpod.itdb_init_ipod(mount, None, None, None)
    print "Done."

if __name__ == '__main__':
    main()
