#include <qapplication.h>
#include <unistd.h>
#include <fstream>
#include <sys/wait.h>   // For WIFEXITED on Mac OS X

#include "mythcontext.h"
#include "mythdbcon.h"
#include "lcddevice.h"
#include "tv.h"
#include "programinfo.h"
#include "uitypes.h"
#include "remoteutil.h"
#include <qdir.h>
#include "installdialog.h"
#include "installsettings.h"
#include "installationtype.h"
#include "mv_common.h"
#include "libmyth/dialogbox.h"
#include <stdlib.h>
#define UPDATE_STATUS_INTERVAL   5000
#define UPDATE_SCREEN_INTERVAL   5000



WelcomeDialog::WelcomeDialog(MythMainWindow *parent,
                            QString window_name,
                            QString theme_filename,
                            const char* name)
:MythThemedDialog(parent, window_name, theme_filename, name)
{
    system("rm -f /tmp/.install_state");
    system("rm -f /tmp/.install_percent");
    system("rm -f /tmp/.install_error");
    install_drive = "" ;
    recording_text = "";
    scheduled_text = "";
    install_text =  "";
    version_text = "";
    I_AM_BUSY = false;
    WORKING_ON_INSTALL = false;
    current_hostname = "";

    gContext->addListener(this);
    m_timeFormat = gContext->GetSetting("TimeFormat", "h:mm AP");
    wireUpTheme();
    assignFirstFocus();

    m_updateStatusTimer = new QTimer(this);
    connect(m_updateStatusTimer, SIGNAL(timeout()), this,
            SLOT(updateStatus()));
    m_updateStatusTimer->start(UPDATE_STATUS_INTERVAL);

    m_updateScreenTimer = new QTimer(this);
    connect(m_updateScreenTimer, SIGNAL(timeout()), this,
            SLOT(updateScreen()));

    m_timeTimer = new QTimer(this);
    connect(m_timeTimer, SIGNAL(timeout()), this,
            SLOT(updateTime()));
    m_timeTimer->start(1000);

    reboot_box = NULL;
    popup = NULL;
    showPopup();
}
void WelcomeDialog::shutdownNow(int rc)
{
    QString NETBOOT = getenv("NETBOOT");
    NETBOOT=NETBOOT.stripWhiteSpace();
    system("rm -f /tmp/.install_state");
    system("rm -f /tmp/.install_percent");
    system("rm -f /tmp/.install_error");
    if (rc == 1)
        system("/sbin/halt");
    else
        system("/sbin/reboot");
 //   system("/usr/bin/killall -9 X");
}

void WelcomeDialog::runLIVECD(void)
{
    cancelPopup();
    ask_validate_network();
    if ( runsettings(true) ==  1  )
    {
        QString PAINTER = gContext->GetSetting("ThemePainter");
        QString startFECmd = ("MYTHCONFDIR=/tmp  mythfrontend -O ThemePainter=" + PAINTER   );
        myth_system(startFECmd.ascii());
    }
    else
    {
        cancelPopup();
        showPopup();
    }


}



int WelcomeDialog::exec()
{
    updateAll();
    return MythDialog::exec();
}



void WelcomeDialog::keyPressEvent(QKeyEvent *e)
{
    bool handled = false;
    QStringList actions;
    gContext->GetMainWindow()->TranslateKeyPress("Welcome", e, actions);
    for (unsigned int i = 0; i < actions.size() && !handled; i++)
    {
        QString action = actions[i];
        handled = true;
        if (action == "ESCAPE")
        {
            return; // eat escape key
        }
        else if (action == "MENU")
        {
            showPopup();
        }
        else if (action == "NEXTVIEW")
        {
            accept();
        }
        else if (action == "SELECT")
        {
            activateCurrent();
        }
        else
            handled = false;
    }

    if (!handled)
        MythThemedDialog::keyPressEvent(e);
}

UITextType* WelcomeDialog::getTextType(QString name)
{
    UITextType* type = getUITextType(name);
    if (!type)
    {
        cout << "ERROR: Failed to find '" << name <<  "' UI element in theme file\n"
            << "Bailing out!" << endl;
        exit(0);
    }
    return type;
}

void WelcomeDialog::wireUpTheme()
{
    m_status_text = getTextType("status_text");
    m_recording_text = getTextType("recording_text");
    m_scheduled_text = getTextType("scheduled_text");
    m_mv_text=getTextType("mythvantage_text");
    m_time_text = getTextType("time_text");
    m_date_text = getTextType("date_text");
    m_warning_text = getTextType("conflicts_text");
    m_warning_text->hide();
    buildFocusList();
}

void WelcomeDialog::closeDialog()
{
    done(1);
}

WelcomeDialog::~WelcomeDialog()
{
    gContext->removeListener(this);
    if (m_updateStatusTimer)
        delete m_updateStatusTimer;

    if (m_updateScreenTimer)
        delete m_updateScreenTimer;

    if (m_timeTimer)
        delete m_timeTimer;
}

void WelcomeDialog::updateTime(void)
{
    QString releasefile="/etc/";
    releasefile.append(RELEASEFILE);

    extern const char *myth_source_version;
    extern const char *myth_source_path;
    QString distro_line;
    QFile file(releasefile);
        if ( file.open(IO_ReadOnly | IO_Translate) )
        {
            QTextStream t( &file );        // use a text stream
            distro_line = t.readLine();
            file.close();
        }


    QString s="";
    //QString s="MythVantage 1.4 Mythtv svn: ";
    s.append(distro_line);
    s.append( " , Mythtv svn:" );
    s.append(myth_source_version);
    s.append("  ");
    s.append(myth_source_path);
    m_date_text->SetText(s);
}

void WelcomeDialog::updateStatus(void)
{
//   checkConnectionToServer();
    updateStatusMessage();
}

void WelcomeDialog::updateScreen(void)
{
    QString cmdtxt;
    cmdtxt=MV_ROOT  ;
    cmdtxt.append("bin/install_proxy.sh " );
    system(cmdtxt);
    recording_text=" ";
    mythvantage_text=" ";
    error_text=" ";
    scheduled_text=" ";
    QFile mystatus("/tmp/.install_state");
    QFile mypercent("/tmp/.install_percent");
    QFile myerror("/tmp/.install_error");
    QFile mylog("/tmp/mythvantage_install.log");
    if ( mystatus.open(IO_ReadOnly | IO_Translate) )
        {
            QTextStream t( &mystatus );        // use a text stream
            scheduled_text = t.readLine();
            mystatus.close();
        }

        if ( mypercent.open(IO_ReadOnly | IO_Translate) )
        {
            QTextStream t( &mypercent );        // use a text stream
            recording_text = t.readLine();
            mypercent.close();
        }

        if ( myerror.open(IO_ReadOnly | IO_Translate) )
        {
            QTextStream t( &myerror );        // use a text stream
            error_text = t.readLine();
            myerror.close();
            scheduled_text = error_text;
            recording_text = "FAILED";
            WORKING_ON_INSTALL = false;
        }

    if ( WORKING_ON_INSTALL )
    {
        if ( mylog.open( IO_ReadOnly| IO_Translate ) )
            {
                QTextStream t( &mylog );
                while ( !t.atEnd() )
                {
                    mythvantage_text=t.readLine();
                }
                mylog.close();
            }
    }
    else
    mythvantage_text="";
    m_recording_text->SetText(recording_text);
    m_scheduled_text->SetText(scheduled_text);
    m_mv_text->SetText(mythvantage_text);

    if ( install_drive != ""  )
        install_text = "";

    m_status_text->SetText(install_text );
    m_updateScreenTimer->start(UPDATE_SCREEN_INTERVAL, true);
    if ( scheduled_text == "Done" )
    {
        Reboot_popup () ;
    }
    // shows the busy box when configuring the system
    if ( scheduled_text == "Configuring system")
    {
        if  ( ! I_AM_BUSY )
        busy_box();
        assignFirstFocus();
    }
};

void WelcomeDialog::busy_box(void)
{
    QString msgtext = "Please wait, " ;
    msgtext.append(current_hostname);
    msgtext.append(" is preparing for life");
    MythBusyDialog *busy = new MythBusyDialog(msgtext);
    busy->start();

    while (  scheduled_text == "Configuring system" )
    {
        qApp->processEvents ();
        usleep(900);
        I_AM_BUSY = true;
    }
    busy->Close();
    I_AM_BUSY = false;
    busy->deleteLater();
}

void WelcomeDialog::busy_find_oldsettings(void)
{
    MythBusyDialog *busy = new MythBusyDialog(
                                            QObject::tr("Importing old settings"));
    busy->start();
    int return_code = 0;
    while (  return_code  == 0 )
    {
        qApp->processEvents ();
        usleep(900);
        I_AM_BUSY = true;
        return_code = myth_system("ps -ef|grep install_proxy.sh|grep -v grep > /dev/null");

    }
    busy->Close();
    I_AM_BUSY = false;
    busy->deleteLater();

}



void WelcomeDialog::updateAll(void)
{
    updateRecordingList();
    updateScheduledList();
}

bool WelcomeDialog::updateRecordingList()
{
    return true;
}

bool WelcomeDialog::updateScheduledList()
{
    updateStatus();
    updateScreen();
    return true;
}

void WelcomeDialog::updateStatusMessage(void)
{

}

void WelcomeDialog::showPopup(void)
{
    if (popup)
        return;
    popup = new MythPopupBox(gContext->GetMainWindow(), "Menu");
    QButton *topButton;
    QLabel *label = popup->addLabel(tr("Menu"), MythPopupBox::Large, false);
    label->setAlignment(Qt::AlignCenter | Qt::WordBreak);
    // This is a bad way to lock the buttons but it works for now.
    if ( scheduled_text.length() <= 2  )
    {
        topButton = popup->addButton(tr("Install or Upgrade "), this,
                                SLOT(Display_2ndpopup()));
        popup->addButton(tr("Run MythFrontend"), this,
                        SLOT(runLIVECD()));
        popup->addButton(tr("Exit"), this,
                    SLOT(closeDialog()));
        popup->addButton(tr("Close menu"), this, SLOT(cancelPopup()));

        popup->ShowPopup(this, SLOT(cancelPopup()));

    }
    else
    {
        topButton= popup->addButton(tr("Exit"), this,
                        SLOT(closeDialog()));
        popup->addButton(tr("Close menu"), this, SLOT(cancelPopup()));

        popup->ShowPopup(this, SLOT(cancelPopup()));
    }

    topButton->setFocus();
}


QString WelcomeDialog::diskmodel(QString drive ,  QString tsize)
{
    string line;
    QString cmdtxt;
    cmdtxt=MV_ROOT  ;
    cmdtxt.append("bin/install_proxy.sh disk_model_it " +  drive + " " + tsize );
    myth_system(cmdtxt);

    ifstream model("/tmp/model");
    if (model.is_open())
            getline (model,line);
    model.close();
    return line;
}

QString WelcomeDialog::findinstallsouce(void)
{
    string line;
    QString currentitem;
    ifstream  mountfile("/proc/mounts");
    //ifstream  mountfile("procmounts");
    while (! mountfile.eof() )
        {
            getline (mountfile,line);
            if ( line.empty() )
                line = "oops didn't find andthing";
            currentitem = line;

            if ( ! currentitem.contains("/dev"))
                currentitem="not the right line";

            //if  ( currentitem.contains("/mnt/live/mnt") )
            if  ( currentitem.contains("/.livesys/medium") )
                {
                    int ndx = line.find(" ");
                        currentitem = line.substr(0,ndx);
                        ndx = currentitem.findRev("/");
                        currentitem = currentitem.mid(ndx+1,3);
                    return currentitem;
                };

        }

};

void WelcomeDialog::showPopup_2(void)
{

    if (popup)
        return;
    popup = new MythPopupBox(gContext->GetMainWindow(), "Select the drive to install");
    findinstallsouce();
    QButton *CancelButton;
    QLabel *label = popup->addLabel(tr("Select the install target."), MythPopupBox::Large, false);
    label->setAlignment(Qt::AlignCenter | Qt::WordBreak);
    string  currentitem;
    string  sizeitem;
    string disksize;
    string line;
    bool installsource = false;

    QString NETBOOT = getenv("NETBOOT");
    NETBOOT=NETBOOT.stripWhiteSpace();
    if ( NETBOOT   == "YES" )
        popup->addButton(("Diskless Frontend " ), this, SLOT(install_net() ) );

    QString  INSTALLSOURCE = findinstallsouce();
     std::cout << "install source:" << std::endl;
     std::cout << INSTALLSOURCE << std::endl;
    ifstream partitions("/proc/partitions");
    if (partitions.is_open())
        while (! partitions.eof() )
        {
            getline (partitions,line);
            if ( line.empty() )
            {
                line = "oops didn't find anything";
            }
            int ndx = line.rfind(" ");
            ndx = ndx +1;
            int linelength = line.length();
            currentitem = line.substr(ndx,linelength);
            sizeitem = line.substr(0,ndx-1);
            linelength = sizeitem.length();
            ndx  = sizeitem.rfind(" ");
            disksize = sizeitem.substr(ndx+1,linelength);

//              std::cout << currentitem<< std::endl;
            if(  currentitem == INSTALLSOURCE  )
            {
                std::cout << currentitem<< std::endl;
                installsource = true;
            }


            if (! installsource  )
                {
                if ( currentitem == "hda" )
                    popup->addButton(("hda  " + diskmodel(currentitem,disksize)), this, SLOT(install_hda() ) );
                if ( currentitem == "hdb" )
                    popup->addButton(("hdb  " + diskmodel(currentitem,disksize)), this, SLOT(install_hdb() ) );
                if ( currentitem == "hdc" )
                    popup->addButton(("hdc  " + diskmodel(currentitem,disksize)), this, SLOT(install_hdc() ) );
                if ( currentitem == "hdd" )
                    popup->addButton(("hdd  " + diskmodel(currentitem,disksize)), this, SLOT(install_hdd() ) );
                if (currentitem == "sda" )
                    popup->addButton(("sda  " + diskmodel(currentitem,disksize)), this, SLOT(install_sda() ) );
                if (currentitem == "sdb" )
                    popup->addButton(("sdb  " + diskmodel(currentitem,disksize)), this, SLOT(install_sdb() ) );
                if (currentitem == "sdc" )
                    popup->addButton(("sdc  "+ diskmodel(currentitem,disksize)), this, SLOT(install_sdc() ) );
                if (currentitem == "sdd" )
                    popup->addButton(("sdd  "+ diskmodel(currentitem,disksize)), this, SLOT(install_sdd() ) );
                }
            installsource = false;
        }
    partitions.close();
    CancelButton = popup->addButton(tr("Cancel"), this, SLOT(MAINPopup()));
    popup->ShowPopup(this, SLOT(cancelPopup()));
    CancelButton->setFocus();
}

void WelcomeDialog::GO_popup(QString go_text)
{
    if (popup)
        return;
    DialogCode  retval = MythPopupBox::Show2ButtonPopup(gContext->GetMainWindow(),
                                QString("Start the process"),
                                QObject::tr(go_text),
                                QObject::tr("Start the process"), QObject::tr("Cancel"), kDialogCodeButton0);

    if ( retval  == kDialogCodeButton0  )
        {
            install_it();
        }
        else
        {
            cancelPopup();
            showPopup();
        }
}


void WelcomeDialog::Reboot_popup(void)
{    if (reboot_box)
        return;
    QString prompt1;
    QFile updbstatus("/tmp/.upgrade_db_failed");
    if ( updbstatus.open(IO_ReadOnly | IO_Translate) )
    {
        prompt1 = QObject::tr(" ");
        prompt1.append("\n");
        prompt1.append("An error occured while attempting to restore the database!");
        prompt1.append("\n");
        prompt1.append("The old database could not be restored, so a new database was created");
        prompt1.append("\n");

    }
    else
    {
        prompt1 = QObject::tr("Ready to go!");
    }



    reboot_box = new DialogBox(gContext->GetMainWindow(),  prompt1);
    reboot_box->AddButton(QObject::tr("Reboot"));
    reboot_box->AddButton(QObject::tr("Power off"));

    int returncode = 0;
    DialogCode  dcode = reboot_box->exec();
    reboot_box->deleteLater();
            if (kDialogCodeButton0 ==  dcode )
                returncode = 0;
            if (kDialogCodeButton1 == dcode )
                returncode = 1;
            if (kDialogCodeButton2 == dcode )
                returncode = 2;


    reboot_box = NULL;
    shutdownNow(returncode);
}



void WelcomeDialog::cancelPopup(void)
{
    if (!popup)
        return;
    popup->hide();
    popup->deleteLater();
    popup = NULL;
    setActiveWindow();
}

void WelcomeDialog::MAINPopup(void)
{
    if (!popup)
        return;
    popup->hide();
    popup->deleteLater();
    popup = NULL;
    showPopup();
    setActiveWindow();
}

void WelcomeDialog::Display_2ndpopup(void)
{
    cancelPopup();
    showPopup_2();
    updateStatusMessage();
    updateScreen();
}

void WelcomeDialog::install_hda(void)
{
    install_drive = "hda" ;
    install_generic();
}

void WelcomeDialog::install_hdb(void)
{
    install_drive = "hdb" ;
    install_generic();
}

void WelcomeDialog::install_hdc(void)
{
    install_drive = "hdc" ;
    install_generic();
}

void WelcomeDialog::install_hdd(void)
{
    install_drive = "hdd" ;
    install_generic();
}

void WelcomeDialog::install_sda(void)
{  install_drive = "sda" ;
    install_generic();
}
void WelcomeDialog::install_sdb(void)
{  install_drive = "sdb" ;
    install_generic();
}

void WelcomeDialog::install_sdc(void)
{  install_drive = "sdc" ;
    install_generic();
}

void WelcomeDialog::install_sdd(void)
{
    install_drive = "sdd" ;
    install_generic();
}

void WelcomeDialog::install_net(void)
{
    install_drive = "NET" ;
    gContext->ActivateSettingsCache(false);
    gContext ->SaveSetting("HOSTinstallationtype","NET");
    install_generic();
}

void WelcomeDialog::install_generic(void)
{
    gContext->ActivateSettingsCache(false);
    cancelPopup();
    updateStatusMessage();
    updateScreen();
    QString installwarningtext;
    int runNextSetting;
    runNextSetting = 1;
    int tflag;
    tflag = 0;
    int retcode;
    retcode=0;
    QString installtype;
    if ( install_drive != "NET")
        retcode = mythinstalltype(install_drive);
    if ( retcode == 0 )
    {
        installtype = gContext -> GetSetting("HOSTinstallationtype");
            if ( installtype == "Full/Auto" )
            {
                runNextSetting = ask_validate_network();
                installwarningtext="Warning!";
                installwarningtext.append ("\n");
                installwarningtext.append ("\n");
                installwarningtext.append  ("About to erase the entire");
                installwarningtext.append ("\n");
                installwarningtext.append  ("installation drive of ");
                installwarningtext.append (install_drive);

            }
            else if ( installtype == "NET")
            {
                runNextSetting=0;
                gContext ->SaveSetting("HostSystemType", "Frontend_only");
                gContext->SaveSetting("HostaccesshostypeSystemtype","0");
                installwarningtext.append  ("About to install ");
                installwarningtext.append ("\n");
                installwarningtext.append (install_drive);
                // ask for hostname
                runsettings(false,true,false,false,false,false,false);
            }
            else if ( installtype == "Upgrade" )
            {
                installwarningtext="Warning!";
                installwarningtext.append ("\n");
                installwarningtext.append ("\n");
                installwarningtext.append  ("About to erase the");
                installwarningtext.append ("\n");
                installwarningtext.append  ("partition ");
                installwarningtext.append (install_drive);
                installwarningtext.append  ("1");
                QString cmdtxt;
                cmdtxt=MV_ROOT  ;
                cmdtxt.append("bin/install_proxy.sh find_update " +  install_drive +" &");
                system(cmdtxt);
                busy_find_oldsettings();
                bool flag = false;
                QString line;
                QString currentitem;
                QFile file("/etc/systemconfig");
                if ( file.open(IO_ReadOnly | IO_Translate) )
                {
                    QTextStream t( &file );        // use a text stream
                    while ( !t.eof() )
                    {
                        line = t.readLine();
                        if ( line.startsWith("hostname"))
                        {
                            flag=true;
                            currentitem = line.section( "=", 1, 1 );
                            current_hostname =  currentitem   ;
                        }
                    }
                    file.close();
                    cout << current_hostname << endl;
                }
                if ( flag )
                {
                    //  GO_popup(installwarningtext);
                        tflag =  1;
                }
                else
                {
                    cout << "searching for knoppmyth-versin" << endl;
                    //couldn't open /etc/systemconfig, so now look for /tmp/etc/Knoppmyth-version
                    QFile file("/tmp/etc/KnoppMyth-version");
                    if ( file.exists() )
                    { //appears to be a knoppmyth version, proceed
                        cout << "found knoppmyth-version" << endl;
                        QFile kmfile("/tmp/etc/hostname");
                        if ( kmfile.open(IO_ReadOnly | IO_Translate) )
                        {
                            QTextStream t( &kmfile );        // use a text stream
                            line = t.readLine();
                            flag=true;
                            currentitem = line.stripWhiteSpace();
                            current_hostname =  currentitem   ;
                            //gContext->ActivateSettingsCache(true);
                            gContext->ClearSettingsCache();
                            gContext->SetSetting("HostMyhostname",current_hostname);
                            gContext->SaveSetting("HostMyhostname",current_hostname);
                        }
                        kmfile.close();
                        cout << current_hostname << endl;
                        runNextSetting = ask_validate_network();
                    }
                    else
                    {
                         //popup things went wrong
                        DialogCode returncode  = MythPopupBox::Show2ButtonPopup(gContext->GetMainWindow(),
                                QString(""),
                                QObject::tr("Couldn't find the old config file, proceed with update?"),
                                QObject::tr("No"), QObject::tr("Yes"), kDialogCodeButton1);
                        if ( returncode == kDialogCodeButton1 )
                        {
                            runNextSetting = ask_validate_network();
                        }
                        else if ( returncode == kDialogCodeButton0 )
                        {
                            runNextSetting = 1;
                        }
                    }

                }
            }

    }


//run through the system settings
if ( runNextSetting == 0 )
{
    tflag = runsettings(false,false,true,true,false,false,false,false,false,false,true,false);

}
else
{
    cancelPopup();
    showPopup();
}

if ( tflag == 1 )
    {
        cancelPopup();
        GO_popup(installwarningtext);
    }
    else
    {
    cancelPopup();
    showPopup();
    }

}

void busy_network(void)
{
    MythBusyDialog *busy = new MythBusyDialog(
                                            QObject::tr("Starting network"));
    busy->start();
    int return_code = 0;
    while (  return_code  == 0 )
    {
        qApp->processEvents ();
        usleep(900);
        return_code = myth_system("ps -ef|grep install_proxy.sh| grep setup_network |grep -v grep > /dev/null");
    }
    busy->Close();
    busy->deleteLater();
}


int  WelcomeDialog::ask_validate_network(void)
{

    QString pop_text="abc";
    int retval = 1;
    while ( retval != 0 )
    {
        int settingsrec =  runsettings(false,true,false,false,false,false,false);
        if ( settingsrec != 1 )
            return 1;
        else
        {
            MythProgressDialog *network_check = NULL;
            network_check = new MythProgressDialog(QObject::tr("Please wait while the network is checked."), 6);
            updateScreen();
            QString cmdtxt;
            cmdtxt=MV_ROOT  ;
            cmdtxt.append("bin/install_proxy.sh network_check_it setup_network &");
            retval =  system(cmdtxt);
            busy_network();
            if (network_check)
            {
                network_check->setProgress(1);
                cmdtxt=MV_ROOT  ;
                cmdtxt.append("bin/install_proxy.sh network_check_it check_self");
                retval =  system(cmdtxt);
                if ( retval != 0 )
                {
                    network_check->Close();
                    pop_text="Could not find myself on the network";
                }
            }

                if ( retval == 0)
                {
                    network_check->setProgress(2);
                    cmdtxt=MV_ROOT  ;
                    cmdtxt.append("bin/install_proxy.sh network_check_it check_gw");
                    retval =  system(cmdtxt);
                    if ( retval != 0 )
                        {
                            network_check->Close();
                            pop_text="Could not locate gateway";
                        }
                }

                if (retval == 0)
                {
                    network_check->setProgress(3);
                    cmdtxt=MV_ROOT  ;
                    cmdtxt.append("bin/install_proxy.sh network_check_it check_ns");
                    retval =  system(cmdtxt);
                    if ( retval != 0 )
                    {
                        network_check->Close();
                        pop_text="Could not locate nameserver";
                    }
                }
                if (retval == 0)
                {
                    network_check->setProgress(4);
                                        cmdtxt=MV_ROOT  ;
                    cmdtxt.append("bin/install_proxy.sh network_check_it check_names");
                    retval =  system(cmdtxt);
                    if ( retval != 0 )
                    {
                        network_check->Close();
                        pop_text="Could not lookup names";
                    }
                }
                if (retval == 0)
                {
                    network_check->setProgress(5);
                                        cmdtxt=MV_ROOT  ;
                    cmdtxt.append("bin/install_proxy.sh network_check_it host_names");
                    retval =  system(cmdtxt);
                    if ( retval != 0 )
                    {
                        network_check->Close();
                        pop_text="Hostname already on the network";
                    }
                }


                network_check->setProgress(6);
                if (network_check)
                    {
                        network_check->Close();
                        network_check->deleteLater();
                    }

                if (retval != 0 )
                {
                   DialogCode  val = MythPopupBox::Show2ButtonPopup(gContext->GetMainWindow(),  QString(""),  QObject::tr(pop_text),                              QObject::tr("Continue"), QObject::tr("Try again"), kDialogCodeButton0);

                    if (kDialogCodeButton0 == val )
                         retval = 0;
                }
        }
    }
return 0;
}


void WelcomeDialog::install_it(void)
{
    QString installtype = gContext -> GetSetting("HOSTinstallationtype");
    QString rootfs = gContext -> GetSetting("HOSTrootfstype");
    QString datafs = gContext -> GetSetting("HOSTdatafstype");
    QString rootsize = gContext -> GetSetting("HOSTOSsize");
    rootsize=rootsize + "000";
    QString usealldata = gContext -> GetSetting("HostUseALLdata");
    QString datasize = gContext -> GetSetting("HOSTDATAsize");
    QString uprootfs = gContext -> GetSetting("HOSTuprootfstype");
    QString useswap = gContext -> GetSetting("HostUseSWAP");
    QString swapsize = gContext -> GetSetting("HOSTSWAPsize");
    if ( installtype != "Upgrade"  )
        current_hostname = gContext->GetSetting("HostMyhostname");
    QString clean_upgrade = getenv("CLEAN_UPGRADE");
    if ( clean_upgrade == "YES" )
        current_hostname = gContext->GetSetting("HostMyhostname");

//get the hostname here if upgrade then use previous declarion of hostname
    if ( usealldata == "1" )
    {
        datasize="ALL";
    }
    else
    {
    datasize=datasize + "000";
    }
    if ( useswap == "0" )
    {
        swapsize="NO";
    };


    if ( installtype == "Full/Auto" )
    {
    QString currentitem;
    QString line;
    QFile file("/proc/meminfo");
     if ( file.open(IO_ReadOnly | IO_Translate) )
     {
        QTextStream t( &file );        // use a text stream
            line = t.readLine();
             if ( line.startsWith("MemTotal:"))
                {
                currentitem = line.simplifyWhiteSpace();
                currentitem = currentitem.section( " ", 1, 1 );
                }
     }
     file.close();
    bool ok;
    int mem = currentitem.toInt( &ok, 10 );     // dec == 0, ok == FALSE
    cout << mem << endl;
    if ( mem >= 500000 )
    {
        cout << gContext -> GetSetting("HostXres")  << endl;
        if ((gContext -> GetSetting("HostXres"))  == "1280x720" )
            {
                gContext->SaveSetting("Theme", "syth-lacquer-wide");
                cout <<"Setting theme to syth-wide" << endl;
            }
    }


    QString cmdtxt=MV_ROOT  ;
    cmdtxt.append("bin/install_proxy.sh full_install_it " + install_drive + " " + rootfs + " " + rootsize + " " +  datafs + " " + datasize + " " + swapsize + "&");
        system(cmdtxt);
      }
    else if  ( installtype == "Upgrade" )
    {
        QString cmdtxt=MV_ROOT  ;
        cmdtxt.append("bin/install_proxy.sh upgrade_it " + install_drive + " " + uprootfs +  "&");
        system(cmdtxt);
    }
    else if (installtype=="NET")
    {
        QString olddb = gContext->GetSetting("HostMysqlserver");
        QString cmdtxt;
        cmdtxt=MV_ROOT  ;
        char localhostname[1024];
        if (gethostname(localhostname, 1024))
        {
            VERBOSE(VB_IMPORTANT,
                    "MCP: Error, could not determine host name." + ENO);
            localhostname[0] = '\0';
        }
        QString h;
        h=localhostname;
        cout << "calling restore_default_settings with  hostname " << h << endl;
        cmdtxt.append("bin/restore_default_settings.sh -c save -t syssettings  -d  127.0.0.1  -h " + h);
        system(cmdtxt);
        cmdtxt=MV_ROOT  ;
        cmdtxt.append("bin/install_proxy.sh NETBOOT  " + install_drive +  "  &");
        system(cmdtxt);
    }
    WORKING_ON_INSTALL = true;
    usleep (500);
    updateScreen();
    usleep (500);
    updateScreen();
    cancelPopup();
}