/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: consoleui.cpp,v 1.1.2.1 2004/07/09 02:03:17 hubbe Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */
/************************************************************************
 * instlib.cpp - Post-install setup program utilities.
 */


/***********************************************************************
 * includes
 */

#include "hxtypes.h"

// system includes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <time.h>

#ifdef _UNIX
#define _CONSOLE
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>

#elif defined(_WIN32)
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#ifndef mkdir
#define mkdir(n,p) mkdir(n)    
#endif // mkdir
#ifndef random
#define random() rand()
#endif // random
#define PATH_MAX MAX_PATH
#endif // _UNIX

#include <sys/stat.h>
#include <errno.h>
#include <sys/types.h>
#include <signal.h>

#if defined _AIX43
#include <strings.h>
#include <sys/termio.h>
#endif

#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>

//hxmisc
#include "md5.h"
#ifdef _WIN32
#include "hxstrutl.h" //strcasecmp
#endif // _WIN32


//#include "package_info.h"
#include "consoleui.h"
#include "passwdtool.h"

#ifdef _CONSOLE
/************************************************************************/
/************************************************************************/
ConsoleUI::ConsoleUI()
    : m_nDotPid(0)
{
}

ConsoleUI::~ConsoleUI()
{
}

/************************************************************************
 */

int
ConsoleUI::ShowMessage(const char* format, ...)
{
    va_list args;
    va_start(args, format);
    int ret = vprintf(format, args);
    va_end (args);
    return ret;
}


int
ConsoleUI::ShowErrorMessage(const char* format, ...)
{
    va_list args;
    va_start(args, format);
    int ret = vprintf(format, args);
    va_end (args);
    return ret;
}


/************************************************************************
 */
char*
ConsoleUI::PromptForItem(const char* szPrompt,
                         const char* szDefault,
                         char**      pszResponse,
                         const char* szMessage)
{
    char szTmp[4096];

    if (szMessage)
    {
        printf ("%s", szMessage);
    }
    if (szPrompt)
    {
        printf ("%s ", szPrompt);
    }
    printf ("[%s]: ", szDefault ? szDefault : "");
    fflush(0);

    if (fgets(szTmp, 4096, stdin))
    {
        size_t len = strlen(szTmp);
        if(len <= 1)
        {
            return NULL;
        }

        char* szResponse = new char[len];
        strncpy(szResponse, szTmp, len-1);
        szResponse[len-1] = '\0'; // wack \n char
        if (pszResponse)
        {
            *pszResponse = szResponse;
        }
        return szResponse;
    }
    else
    {
        return NULL;
    }
}

/************************************************************************
 */
void
ConsoleUI::WaitForEnter(const char* szPrompt)
{
    char szTmp[4096];
    if (szPrompt)
        printf ("%s", szPrompt);
    fgets(szTmp, 4096, stdin);
    return;
}

/************************************************************************
 */
void
ConsoleUI::ClearScreen(void)
{
    printf("\n");
    system("clear");
}

/************************************************************************
 */
const char*
ConsoleUI::GetPagerCmd()
{
    static const char* szMore=0;
    if (!szMore)
    {
        szMore = getenv("PAGER");
    }
    if (!szMore)
    {
        szMore = (char*)"more";
    }
    return szMore;
}

/************************************************************************
 */
void
ConsoleUI::DisplayTextFile (const char* szFile)
{
    char szCmd[1024];
    sprintf (szCmd, "%s %s", GetPagerCmd(), szFile);
    xprintf (("executing: %s\n", szCmd));
    system (szCmd);
}


/************************************************************************
 */
void
ConsoleUI::DisplayText (const char* szText)
{
    if (szText)
    {
        FILE* fp = fopen("_license.txt", "w");
        fprintf(fp, "%s", szText);
        fclose(fp);
        DisplayTextFile("_license.txt");
        unlink("_license.txt");
    }
}


/************************************************************************
 */
void
ConsoleUI::PromptForUsernamePassword(char**      pszUsername,
                                     char**      pszPassword,
                                     const char* szMessage)
{
    char* szPassword2=0;

    ShowMessage (szMessage);

    while (!*pszUsername || !strlen(*pszUsername) ||
           !*pszPassword || !strlen(*pszPassword))
    {
        PromptForItem("Username", *pszUsername, pszUsername, "");
        while (!*pszUsername || !strlen(*pszUsername))
        {
            ShowErrorMessage ("Username not specified!\n");
            PromptForItem("Username", *pszUsername, pszUsername, "");
        }
        SetEchoOff();
        *pszPassword = 0;
        while (!*pszPassword)
        {
            PromptForItem("Password", "", pszPassword, "");
            ShowMessage("\n");
            if (!PasswordTool::PasswordIsOK(*pszUsername, *pszPassword))
            {
                *pszPassword = 0;
                ShowErrorMessage("Invalid password entered, try again.\n");
            }
        }
        char* szPassword2=0;
        while (!szPassword2)
        {
            PromptForItem("Confirm Password", "", &szPassword2, "");
            ShowMessage("\n");
            if (!PasswordTool::PasswordIsOK(*pszUsername, szPassword2))
            {
                szPassword2 = 0;
                ShowErrorMessage("Invalid password entered, try again.\n");
            }
        }
        SetEchoOn();
        if (strcmp (*pszPassword, szPassword2) != 0)
        {
            ShowErrorMessage ("Passwords don't match!\n");
            WaitForEnter ("Press [Enter] to try again.");
            *pszPassword = 0;
        }
    }
}


/************************************************************************
 */
void
ConsoleUI::SetEchoOff(void)
{
    ioctl(0, TCGETS, &m_oldtty);
    struct termios tty = m_oldtty;
    tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL);
    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 0;
    ioctl(0, TCSETS, &tty);
}

void
ConsoleUI::SetEchoOn(void)
{
    ioctl(0, TCSETS, &m_oldtty);
}


/***********************************************************************
 * StartPrintingDots / StopPrintingDots
 *
 * Fork off a process that just prints "."'s once a second to 
 * indicate the installer is busy.
 */

void
ConsoleUI::StartPrintingDots(void)
{
    int nDotCount=0;
    if (m_nDotPid)
        StopPrintingDots();

    m_nDotPid = fork();
    if (m_nDotPid == 0)
    {
        while (1)
        {
            sleep (2);  // one second's too often, let's do two
            printf (".");
            fflush(0);

            //don't print dots forever, in the remote case we've
            //been orphaned or the caller is hung
            if (++nDotCount > 30)
            {
                exit(0);
            }
        }
    }
}

void
ConsoleUI::StopPrintingDots(void)
{
    if (m_nDotPid)
    {
        kill (m_nDotPid, 15);
    }
    m_nDotPid = 0;
}


/************************************************************************
 * ConsoleUI::PrintUsage - Print command-line usage information
 *
 * Not to be confused with Stage1PrintUsage() in rsarchive.cpp.
 */
void
ConsoleUI::PrintUsage(const char* szProgName, const char* szOpt)
{
    if (szOpt)
    {
        fprintf (stderr, "Error: unknown option %s\n\n", szOpt);
    }

    // strip off any path information
    char* pName = (char*)szProgName + strlen(szProgName);
    while (pName > szProgName && *pName != '/' && *pName != '\\')
    {
        --pName;
    }
    if (*pName == '/' || *pName == '\\')
    {
        ++pName;
    }

    fprintf(stderr, "Usage: %s [options]\n", pName);
#ifdef PACKAGE_CMDLINE_HELP
    fprintf(stderr, "\nWhere options are:\n%s\n", PACKAGE_CMDLINE_HELP);
#endif
}

#else //_CONSOLE
/************************************************************************/
/************************************************************************/
ConsoleUI::ConsoleUI()
{
   // stub
}

ConsoleUI::~ConsoleUI()
{
   // stub
}

/************************************************************************
 */

#endif // _CONSOLE
