# Fixes migrations for people who are coming pre-current migrations :)

import os
import sys
import pymongo

print "*** WARNING! ***"
print "  This script is ONLY for people who have data pre-modern migrations."
print "  If that's not you, don't run this!"
print "  Also makes the following assumptions:"
print "    - that you're running this on local branch 'master'"
print "    - that your master branch is up to date with latest mediagoblin"
print "      master"
print "    - You're running on database 'mediagoblin' on standard"
print "      connection parameters"
print "    - You're running this out of buildout"
print "    - That you don't have any modified files in your git checkout"
print ""
print "Consider yourself warned!"

run_it = raw_input(
    'Are you SURE you want to run this? (if so, type "yes")> ')

if not run_it == 'yes':
    sys.exit(1)

print "~*** First applying old migrations... ***~\n"
os.popen('git checkout 6ae8b541f957b49ae86051814097e769d20f29af')
os.popen('echo "Old migrations running..." > migration_result.txt')
os.popen('echo "=========================" >> migration_result.txt')
os.popen('./bin/gmg migrate >> migration_result.txt')

print "~*** Okay, now making sure your database is unmigrated... ***~\n"
db = pymongo.Connection()['mediagoblin']
db.drop_collection('app_metadata')
db['app_metadata'].update(
    {u'_id': u'mediagoblin'},
    {u'$set': {u'current_migration': 0}},
    upsert=True)

print "~*** Checking back out master and running migrations... ***~\n"
os.popen('git checkout master')
os.popen('echo "\nNew migrations running..." >> migration_result.txt')
os.popen('echo "=========================" >> migration_result.txt')
os.popen('./bin/gmg migrate >> migration_result.txt')

print "done, migration output available in migration_result.txt"
