#! /usr/bin/python

import os
import glob
import re
import shutil


def fix1():
    XML_ROOT = '/usr/local/id/hdvr/current/conf/xml'
    fs = glob.glob(os.path.join(XML_ROOT, 'mdpersist-010-cm-*-CameraSetupBasic.xml'))
    
    for fn in fs:
        f = open(fn, 'r')
        c = f.read()
        f.close()
        
        c1 = re.sub('<UserName>.*</UserName>', '<UserName>admin</UserName>', c)
        c2 = re.sub('<Password>.*</Password>', '<Password>Vcmcef3965</Password>', c1)
        
        os.unlink(fn)
        f = open(fn, 'w')
        f.write(c2)
        f.close()

print '============================================='
print '===           Warning!!!                  ==='
print '============================================='
print 'The program will turn off the service of data archiving during the process.'
print 'After the process finished, the system will reboot.'

a1 = raw_input("Continue? (y or n)")
if a1 == 'y':
    if not os.path.exists('/Share/usr.sfs'):
        print "/Share/usr.sfs is missing!"
        print "failed!!"
    else:
        print "........................"
        os.system('svc -d -k /service/as')
        print "........................"
        cfhd = open('/boot/cfhd').read().strip()
        os.system('mount /dev/%s /mnt'%(cfhd))
        print "........................"
        f1 = os.popen('mount|grep mnt')
        if cfhd in f1.read():
            shutil.copy('/Share/usr.sfs', '/mnt')
            print "........................"
            shutil.copy('/Share/run', '/mnt/etc/service/as')
            print "........................"
            os.system('sync')
            print "........................"
            os.system('umount /mnt')
            print "........................"
            fix1()
            print "........................"
            a2 = raw_input("Reboot? (y or n)")
            if a2 == 'y':
                os.system('reboot')
        
print 'bye!'




