
////////////////////////////////////////////////////////////////////////////////
//
//    File Name:  Setup.rul
//
//  Description:  Windows NT InstallShield script for the Network Time Protocol
//
//     Comments:  This template script performs setup for the Network Time
//                Protocol Service.
//
//	History:	Created by Greg Schueman for NTP 	1998/6/29 (yyyy/mm/dd)
//
////////////////////////////////////////////////////////////////////////////////


// Include header files

	#include "service.h"
    #include "sdlang.h"
    #include "sddialog.h"

////////////////////// string defines ////////////////////////////

    #define UNINST_LOGFILE_NAME      "Uninst.isu"
	#define	EVENTLOG_ENTRY "\\SYSTEM\\CurrentControlSet\\Services\\Eventlog\\Application\\NTP"
	#define	SERVICE_ENTRY  "\\SYSTEM\\CurrentControlSet\\Services\\NetworkTimeProtocol"
	#define ONETIMESOURCE           1
	#define TWOTIMESOURCES          2
	#define NOTIMEYET               3
	

//////////////////// installation declarations ///////////////////

// ----- DLL defines -----
	#define k_PrivilegeErr                  1
	#define k_CreateKeyErr                  2
	#define k_RestoreKeyErr                 3
	#define k_ErrUnableToOpenWriteOwner     4
	#define k_ErrUnableToSetOwner           5
	#define k_ErrUnableToOpenDAC            6
	#define k_ErrUnableToWriteDACL          7
	#define k_OpenKeyError                  8
	#define k_ModifySetAccountFail          10
	#define k_SCMErr                        11
	#define k_SCMpoErr                      12
	#define k_DeleteServiceFail             13
	#define k_DeleteKeyFail                 14
	#define k_DeleteValueFail               15
	#define k_DirSecurityErr                16
	#define k_DirSetDACLErr                 17
	#define k_DirSetSecurityErr             18
	#define k_SCMpoStopErr                  19
	#define k_SaveKeyErr                    20
	#define k_ServiceUnknownErr             50
	#define k_ServiceDependency             51
	#define k_ServiceDependencyFail         52
	#define k_ServiceLogonFail              53

	#define k_BadPath                       101
	#define k_AccessDenied                  102
	#define k_ServiceExists                 103
	#define k_createservicefailed           104
	#define k_removeservicefailed           105
	#define k_ServicenoExists               106


    // your DLL function prototypes


// ---- script function prototypes -----

    // generated by the Project Wizard
    prototype ShowDialogs();
    prototype MoveFileData();
    prototype HandleMoveDataError( NUMBER );
    prototype ProcessBeforeDataMove();
    prototype ProcessAfterDataMove();
    prototype SetupRegistry();
    prototype SetupFolders();
    prototype SetupService();
    prototype CleanUpInstall();
    prototype SetupInstall();
    prototype SetupScreen();
    prototype CheckRequirements();
    prototype DialogShowSdWelcome();
    prototype DialogShowSdLicense();
    prototype DialogShowSdShowInfoList();
    prototype DialogShowSdRegisterUser();
    prototype DialogShowSdAskDestPath();
    prototype DialogShowSdSetupType();
    prototype DialogShowSdComponentDialog2();
    prototype DialogShowSdSelectFolder();
    prototype DialogShowSdStartCopy();
    prototype DialogShowSdFinishReboot();

    // your script function prototypes
	prototype RemoveNTP                     ();
	prototype ReportError                   (INT, BYREF STRING);
	prototype DoConfigType                  ();
	prototype CreateConfigFiles             (INT);
	prototype RegisterEventlogMessages	    (STRING);
	prototype CheckForService               ();
	prototype GetImagePath                  (BYREF STRING);


    // ----- global variables ------

	STRING  svDir, szMsg, szFileSet,szTitle,  szMessage, svUninstLogFile;
	STRING  szProgram, szParam, szTemp, szTemp2, szAppPath;
	STRING  svFileName;
	STRING  svTempStr;
	STRING  svModuleDir;
	STRING  svAnswer;
	STRING  dummy;
	STRING  svNTPAddress;                   // the IP address of "1st" time source
	STRING  svNTPAddress2;                  // the IP address of "2nd" time source
	
	BOOL    bRemoveNTP, bUpdateModules;
	
	NUMBER  nReturnValue;
    INT     nReturnValue2;
    INT     nValue;
	


    // generated by the Project Wizard
    BOOL        bWinNT, bIsShellExplorer, bInstallAborted, bIs32BitSetup;
    STRING      svName, svCompany, svSerial;
    STRING      svDefGroup;
    STRING      svSetupType;
    LIST        listStartCopy;


    // your global variables


///////////////////////////////////////////////////////////////////////////////
//
//   MAIN PROGRAM
//
//      The setup begins here by hiding the visible setup
//      window.  This is done to allow all the titles, images, etc. to
//      be established before showing the main window.  The setup is
//      then performed in a series of calls to script defined functions,
//      with error checking at each step.
//
///////////////////////////////////////////////////////////////////////////////
program
    Disable( BACKGROUND );

	dummy = "   ";
    // Set default registry tree
    RegDBSetDefaultRoot(HKEY_LOCAL_MACHINE);

    CheckRequirements();

    SetupInstall();

    SetupScreen();

    if (ShowDialogs()<0) goto end_install;

    if (ProcessBeforeDataMove()<0) goto end_install;

    if (MoveFileData()<0) goto end_install;

    if (ProcessAfterDataMove()<0) goto end_install;

    if (SetupRegistry()<0) goto end_install;

    if (SetupFolders()<0) goto end_install;


    end_install:

    CleanUpInstall();

    // If an unrecoverable error occurred, clean up
    // the partial installation. Otherwise, exit normally.

    if (bInstallAborted) then
        abort;
    endif;

endprogram


///////////////////////////////////////////////////////////////////////////////
//
// Function:  ShowDialogs
//
//  Purpose:  This function manages the display and navigation of
//            the standard dialogs that exist in a setup.
//
///////////////////////////////////////////////////////////////////////////////
function ShowDialogs()
    NUMBER  nResult;

begin

    Dlg_Start:
    // beginning of dialogs label

    Dlg_SdWelcome:
    nResult = DialogShowSdWelcome();
    if (nResult = BACK) goto Dlg_Start;

    Dlg_SdLicense:
    nResult = DialogShowSdLicense();
    if (nResult = BACK) goto Dlg_SdWelcome;

    Dlg_SdShowInfoList:
    nResult = DialogShowSdShowInfoList();
    if (nResult = BACK) goto Dlg_SdLicense;

    Dlg_SdRegisterUser:
    nResult = DialogShowSdRegisterUser();
    if (nResult = BACK) goto Dlg_SdShowInfoList;

    Dlg_SdAskDestPath:
    nResult = DialogShowSdAskDestPath();
    if (nResult = BACK) goto Dlg_SdRegisterUser;

    Dlg_SdSetupType:
    nResult = DialogShowSdSetupType();
    if (nResult = BACK) goto Dlg_SdAskDestPath;

    Dlg_SdComponentDialog2:
    if ((nResult = BACK) && (svSetupType != "Custom") && (svSetupType != "")) then
        goto Dlg_SdSetupType;
    endif;
    nResult = DialogShowSdComponentDialog2();
    if (nResult = BACK) goto Dlg_SdSetupType;

    Dlg_SdSelectFolder:
    nResult = DialogShowSdSelectFolder();
    if (nResult = BACK) goto Dlg_SdComponentDialog2;

    Dlg_SdStartCopy:
    nResult = DialogShowSdStartCopy();
    if (nResult = BACK) goto Dlg_SdSelectFolder;

    return 0;

end;


///////////////////////////////////////////////////////////////////////////////
//
// Function: ProcessBeforeDataMove
//
//  Purpose: This function performs any necessary operations prior to the
//           actual file transfer.
//
///////////////////////////////////////////////////////////////////////////////
function ProcessBeforeDataMove()
    STRING svLogFile;
    NUMBER nResult;

begin

  // Create app information, uninstallation, and App Paths registry keys.

    InstallationInfo( @COMPANY_NAME, @PRODUCT_NAME, @PRODUCT_VERSION, @PRODUCT_KEY );

    svLogFile = UNINST_LOGFILE_NAME;

    nResult = DeinstallStart( svDir, svLogFile, @UNINST_KEY, 0 );
    if (nResult < 0) then
        MessageBox( @ERROR_UNINSTSETUP, WARNING );
    endif;

    szAppPath = TARGETDIR; // TO DO : if your application .exe is in a subfolder
                           // of TARGETDIR then add subfolder

    if ((bIs32BitSetup) && (bIsShellExplorer)) then
        RegDBSetItem( REGDB_APPPATH, szAppPath );
        RegDBSetItem( REGDB_APPPATH_DEFAULT, szAppPath ^ @PRODUCT_KEY );
        RegDBSetItem( REGDB_UNINSTALL_NAME, @UNINST_DISPLAY_NAME );
    endif;

    // TO DO : any other tasks you want to perform before file transfer
	ISQueryServices();  // Shutdown service if running
	DoConfigType();     // Setup ntp.conf Service Configuration File


// install drops through


    return 0;
end;


///////////////////////////////////////////////////////////////////////////////
//
//  Function:  MoveFileData
//
//  Purpose:  This function handles the file transfer for
//            the setup.
//
///////////////////////////////////////////////////////////////////////////////
function MoveFileData()
    NUMBER nResult, nDisk;

begin

    nDisk = 1;
    SetStatusWindow( 0, "" );
    Disable( DIALOGCACHE );
    Enable( STATUS );
    StatusUpdate( ON, 100 );
    nResult = ComponentMoveData( MEDIA, nDisk, 0 );

    HandleMoveDataError( nResult );

    Disable( STATUS );

    return nResult;

end;


///////////////////////////////////////////////////////////////////////////////
//
// Function: HandleMoveDataError
//
//  Purpose: This function handles the error (if any) during the file transfer
//           operation.
//
///////////////////////////////////////////////////////////////////////////////
function HandleMoveDataError( nResult )
    STRING szErrMsg, svComponent , svFileGroup , svFile;

begin

    svComponent = "";
    svFileGroup = "";
    svFile = "";

    switch (nResult)
        case 0:
            return 0;
        default:
            ComponentError ( MEDIA , svComponent , svFileGroup , svFile , nResult );
            szErrMsg = @ERROR_MOVEDATA  + "\n\n" +
                @ERROR_COMPONENT + " " + svComponent + "\n" +
                @ERROR_FILEGROUP + " " + svFileGroup + "\n" +
                @ERROR_FILE      + " " + svFile;
            SprintfBox( SEVERE, @TITLE_CAPTIONBAR, szErrMsg, nResult );
            bInstallAborted = TRUE;
            return nResult;
    endswitch;

end;


///////////////////////////////////////////////////////////////////////////////
//
// Function: ProcessAfterDataMove
//
//  Purpose: This function performs any necessary operations needed after
//           all files have been transferred.
//
///////////////////////////////////////////////////////////////////////////////
function ProcessAfterDataMove()
    STRING szReferenceFile;

begin

    // TO DO : update self-registered files and other processes that
    //        should be performed after the files have been transferred.

    // DeinstallSetReference specifies a file to be checked before
    // uninstallation. If the file is in use, uninstallation will not proceed.

    szReferenceFile = svDir ^ @PRODUCT_KEY; // TO DO : If your file is in a
                                            // subfolder of svDir add that here
    DeinstallSetReference( szReferenceFile );
	ISInstallServices();

   	if (AskYesNo("Setup is complete.  The NTP service is installed.\n"+
				"Do you want to look at the documentation for NTP?\n",
				 YES) = YES) then
	    LaunchAppAndWait("WRITE.EXE",TARGETDIR ^ "ntpog.wri",1);
   	endif;

	return 0;
end;


///////////////////////////////////////////////////////////////////////////////
//
// Function: SetupRegistry
//
//  Purpose: This function makes the registry entries for this setup.
//
///////////////////////////////////////////////////////////////////////////////
function SetupRegistry()
    NUMBER nResult;
	NUMBER nvSize;
	STRING svTemp;
	
begin

    // TO DO : Add all your registry entry keys here.
    // Call registry functions and/or create keys from
    // the InstallShield IDE's Resources pane.
    //
	//    RegDBCreateKeyEx, RegDBSetKeyValueEx....
	//
	svTemp = TARGETDIR^"ntpd.exe";
	RegDBSetDefaultRoot(HKEY_LOCAL_MACHINE);
	RegDBSetKeyValueEx(EVENTLOG_ENTRY,"EventMessageFile",REGDB_STRING,svTemp,nvSize);
	RegDBSetKeyValueEx(EVENTLOG_ENTRY,"TypeSupported",REGDB_NUMBER,"7",nvSize);


    nResult = CreateRegistrySet( "" );

    return nResult;
 end;


///////////////////////////////////////////////////////////////////////////////
//
// Function: SetupFolders
//
//  Purpose: This function creates all the folders and shortcuts for the
//           setup.  This includes program groups and items for Windows 3.1.
//
///////////////////////////////////////////////////////////////////////////////
function SetupFolders()
    NUMBER nResult;

begin


    // TO DO : Add all your folders (or program groups) along with shortcuts (or
    // program items). Call CreateProgramFolder and AddFolderIcon, and/or create
    // shortcuts etc. from the InstallShield IDE's Resources pane.
    //
    // Note : for 16-bit setups you should add an uninstaller icon pointing to
    //        your log file.  Under 32-bit this is automatically done by Windows.

    nResult = CreateShellObjects( "" );

    return nResult;
 end;


///////////////////////////////////////////////////////////////////////////////
//
// Function: CleanUpInstall
//
//  Purpose: This cleans up the setup.  Anything that should
//           be released or deleted at the end of the setup should
//           be done here.
//
///////////////////////////////////////////////////////////////////////////////
function CleanUpInstall()

begin

    ListDestroy( listStartCopy );

    if (bInstallAborted) then
        return 0;
    endif;

    DialogShowSdFinishReboot();

    if (BATCH_INSTALL) then // ensure locked files are properly transferred
        CommitSharedFiles(0);
    endif;

    return 0;
end;


///////////////////////////////////////////////////////////////////////////////
//
// Function: SetupInstall
//
//  Purpose: This will initialize the setup.  Any general initialization
//           needed for the installation should be performed here.
//
///////////////////////////////////////////////////////////////////////////////
function SetupInstall()
 STRING sTemp;

begin

    Enable( CORECOMPONENTHANDLING );

    bInstallAborted = FALSE;

    //  Create list of end user selections to be displayed by DialogShowSdStartCopy()  //

    listStartCopy = ListCreate(STRINGLIST);

    ListAddString( listStartCopy, "Network Time Protocol Server Installation Options:", AFTER );

    if (bIs32BitSetup) then
        svDir = PROGRAMFILES ^ @COMPANY_NAME ^ @PRODUCT_NAME;
    else
        svDir = PROGRAMFILES ^ @COMPANY_NAME16 ^ @PRODUCT_NAME16; // use short names
    endif;

    TARGETDIR  = svDir;

    SdProductName( @PRODUCT_NAME );

    Enable( DIALOGCACHE );

    return 0;
end;


///////////////////////////////////////////////////////////////////////////////
//
// Function:  SetupScreen
//
//  Purpose:  This function establishes the screen look.  This includes
//            colors, fonts, and text to be displayed.
//
///////////////////////////////////////////////////////////////////////////////
function SetupScreen()

begin

    Enable( FULLWINDOWMODE );
    Enable( INDVFILESTATUS );
    SetTitle( @TITLE_MAIN, 24, WHITE );

    SetTitle( @TITLE_CAPTIONBAR, 0, BACKGROUNDCAPTION ); // Caption bar text.

    Enable( BACKGROUND );

    Delay( 1 );
end;


///////////////////////////////////////////////////////////////////////////////
//
// Function:  CheckRequirements
//
//  Purpose:  This function checks all minimum requirements for the
//            application being installed.  If any fail, then the user
//            is informed and the setup is terminated.
//
///////////////////////////////////////////////////////////////////////////////
function CheckRequirements()
    NUMBER  nvDx, nvDy, nvResult;
    STRING  svResult;

begin

    bWinNT           = FALSE;
    bIsShellExplorer = FALSE;

    // Check screen resolution.
    GetExtents( nvDx, nvDy );

    if (nvDy < 480) then
        MessageBox( @ERROR_VGARESOLUTION, WARNING );
        abort;
    endif;

    // set 'setup' operation mode
    bIs32BitSetup = TRUE;
    GetSystemInfo( ISTYPE, nvResult, svResult );
    if (nvResult = 16) then
        bIs32BitSetup = FALSE; // running 16-bit setup
        return 0; // no additional information required
    endif;

    // --- 32-bit testing after this point ---

    // Determine the target system's operating system.
    GetSystemInfo( OS, nvResult, svResult );

    if (nvResult =  IS_WINDOWSNT) then
        // Running Windows NT.
        bWinNT = TRUE;

        // Check to see if the shell being used is EXPLORER shell.
        if (GetSystemInfo( OSMAJOR, nvResult, svResult ) = 0) then
            if (nvResult >= 4) then
                bIsShellExplorer = TRUE;
            endif;
        endif;

    elseif (nvResult = IS_WINDOWS95 ) then
        bIsShellExplorer = TRUE;

    endif;

end;


///////////////////////////////////////////////////////////////////////////////
//
// Function: DialogShowSdWelcome
//
//  Purpose: This function handles the standard welcome dialog.
//
//
///////////////////////////////////////////////////////////////////////////////
function DialogShowSdWelcome()
    NUMBER nResult;
    STRING szTitle, szMsg;

begin

    szTitle = "";
    szMsg   = "";
    nResult = SdWelcome( szTitle, szMsg );

    return nResult;
end;


///////////////////////////////////////////////////////////////////////////////
//
// Function: DialogShowSdLicense
//
//  Purpose: This function displays the license agreement dialog.
//
//
///////////////////////////////////////////////////////////////////////////////
function DialogShowSdLicense()
    NUMBER nResult;
    STRING szTitle, szMsg, szQuestion, szLicenseFile;

begin

    szLicenseFile = SUPPORTDIR ^ "license.txt";
    szTitle    = "";
    szMsg      = "";
    szQuestion = "";
    nResult    = SdLicense( szTitle, szMsg, szQuestion, szLicenseFile );

    return nResult;
end;


///////////////////////////////////////////////////////////////////////////////
//
// Function: DialogShowSdShowInfoList
//
//  Purpose: This function displays the general information list dialog.
//
//
///////////////////////////////////////////////////////////////////////////////
function DialogShowSdShowInfoList()
    NUMBER nResult;
    LIST   list;
    STRING szTitle, szMsg, szFile;

begin

    szFile = SUPPORTDIR ^ "infolist.txt";

    list = ListCreate( STRINGLIST );
    ListReadFromFile( list, szFile );
    szTitle  = "";
    szMsg    = " ";
    nResult  = SdShowInfoList( szTitle, szMsg, list );

    ListDestroy( list );

    return nResult;
end;


///////////////////////////////////////////////////////////////////////////////
//
// Function: DialogShowSdRegisterUser
//
//  Purpose: This function displays the user registration dialog.
//
//
///////////////////////////////////////////////////////////////////////////////
function DialogShowSdRegisterUser()
    NUMBER nResult;
    STRING szTitle, szMsg;

begin


    svName    = "";
    svCompany = "";

    szTitle = "";
    szMsg   = "";
    nResult = SdRegisterUser( szTitle, szMsg, svName, svCompany);

    return nResult;
end;


///////////////////////////////////////////////////////////////////////////////
//
// Function: DialogShowSdAskDestPath
//
//  Purpose: This function asks the user for the destination folder.
//
///////////////////////////////////////////////////////////////////////////////
function DialogShowSdAskDestPath()
    NUMBER nResult;
    STRING szTitle, szMsg;

begin

    szTitle = "";
    szMsg   = "";
    nResult = SdAskDestPath( szTitle, szMsg, svDir, 0 );

    TARGETDIR = svDir;

    return nResult;
end;


///////////////////////////////////////////////////////////////////////////////
//
// Function: DialogShowSdSetupType
//
//  Purpose: This function displays the standard setup type dialog.
//
///////////////////////////////////////////////////////////////////////////////
function DialogShowSdSetupType()
    NUMBER nResult;
    STRING szTitle, szMsg;

begin

    if (svSetupType = "") then
        svSetupType = "Server";
    endif;

    szTitle = "";
    szMsg   = "";
    nResult = SdSetupTypeEx( szTitle, szMsg, "", svSetupType, 0 );

    return nResult;
end;


///////////////////////////////////////////////////////////////////////////////
//
// Function: DialogShowSdComponentDialog2
//
//  Purpose: This function displays the custom component dialog.
//
//
///////////////////////////////////////////////////////////////////////////////
function DialogShowSdComponentDialog2()
    NUMBER nResult;
    STRING szTitle, szMsg;

begin

    if ((svSetupType != "Custom") && (svSetupType != "")) then
        return 0;
    endif;

    szTitle  = "";
    szMsg    = "";
    nResult  = SdComponentDialog2( szTitle, szMsg, svDir, "" );

    return nResult;
end;


///////////////////////////////////////////////////////////////////////////////
//
//  Function: DialogShowSdSelectFolder
//
//  Purpose: This function displays the standard folder selection dialog.
//
//
///////////////////////////////////////////////////////////////////////////////
function DialogShowSdSelectFolder()
    NUMBER nResult;
    STRING szTitle, szMsg;

begin

    if (SHELL_OBJECT_FOLDER = "") then
        SHELL_OBJECT_FOLDER = @FOLDER_NAME;
    endif;

    szTitle    = "";
    szMsg      = "";
    nResult    = SdSelectFolder( szTitle, szMsg, SHELL_OBJECT_FOLDER );

    return nResult;
end;


///////////////////////////////////////////////////////////////////////////////
//
//  Function: DialogShowSdStartCopy
//
//  Purpose: This function displays the dialog preceding the start of the
//           file transfer process.
//
///////////////////////////////////////////////////////////////////////////////
function DialogShowSdStartCopy()
    NUMBER nResult;
    STRING szTitle, szMsg, sTemp;

begin

	ListAddString( listStartCopy, " SetupType:", AFTER );
    Sprintf(sTemp,"      %s", svSetupType);
    ListAddString( listStartCopy, sTemp, AFTER );
    ListAddString( listStartCopy, " ", AFTER );
    ListAddString( listStartCopy, " TargetDir:", AFTER );
    Sprintf(sTemp,"      %s", TARGETDIR);
    ListAddString( listStartCopy, sTemp, AFTER );
    ListAddString( listStartCopy, " ", AFTER );
    ListAddString( listStartCopy, " User Information:", AFTER );
    Sprintf(sTemp,"      Name:  %s", svName);
    ListAddString( listStartCopy, sTemp, AFTER );
    Sprintf(sTemp,"      Company:  %s", svCompany);
    ListAddString( listStartCopy, sTemp, AFTER );

    szTitle = "";
    szMsg   = "";
    nResult = SdStartCopy( szTitle, szMsg, listStartCopy );

    return nResult;
end;


///////////////////////////////////////////////////////////////////////////////
//
//  Function: DialogShowSdFinishReboot
//
//  Purpose: This function will show the last dialog of the product.
//           It will allow the user to reboot and/or show some readme text.
//
///////////////////////////////////////////////////////////////////////////////
function DialogShowSdFinishReboot()
    NUMBER nResult, nDefOptions;
    STRING szTitle, szMsg1, szMsg2, szOption1, szOption2;
    NUMBER bOpt1, bOpt2;

begin

    if (!BATCH_INSTALL) then
        bOpt1 = FALSE;
        bOpt2 = FALSE;
        szMsg1 = "";
        szMsg2 = "";
        szOption1 = "";
        szOption2 = "";
        nResult = SdFinish( szTitle, szMsg1, szMsg2, szOption1, szOption2, bOpt1, bOpt2 );
        return 0;
    endif;

    nDefOptions = SYS_BOOTMACHINE;
    szTitle     = "";
    szMsg1      = "";
    szMsg2      = "";
    nResult     = SdFinishReboot( szTitle, szMsg1, nDefOptions, szMsg2, 0 );

    return nResult;
end;


// --- Additional sections from previous InstallShield3 script


///////////////////////////////////////////////////////////////////////////////
//
//  Function: CheckForService
//
//  Purpose: This function will determine whether NTP is already installed.
//
///////////////////////////////////////////////////////////////////////////////
function CheckForService()
    STRING temp;
	NUMBER nvSize;
	NUMBER nvType;

begin
	RegDBSetDefaultRoot(HKEY_LOCAL_MACHINE);
        if (RegDBGetKeyValueEx(SERVICE_ENTRY,
			"ImagePath",nvType,temp,nvSize) < 0) then
		return 0;
	endif;
 return -1;
end;


///////////////////////////////////////////////////////////////////////////////
//
//  Function: GetImagePath
//
//  Purpose: Get the given value, under the given key, from the registry.
//
//  History:  Larry Kahn	Created		1996/1/1 (yyyy/mm/dd)
//
///////////////////////////////////////////////////////////////////////////////
function GetImagePath(svValue)
	NUMBER nvSize;
	NUMBER nvType;

begin
        RegDBSetDefaultRoot(HKEY_LOCAL_MACHINE);
        if (RegDBGetKeyValueEx(SERVICE_ENTRY,
              "ImagePath",nvType,svValue,nvSize) < 0) then
		return -1;
	endif;
			
	StrSub(svValue,svValue,0,nvSize - 10);                       // trim to REAL length
        return 0;
end;


///////////////////////////////////////////////////////////////////////////////
//
//  Function: DoConfigType
//
//  Purpose: Find out what type of installation the user is planning,
//           and then create and/or show the configuration files to them.
//
//  History:  Greg Schueman	Created		1996/1/1 (yyyy/mm/dd)
//
///////////////////////////////////////////////////////////////////////////////
function DoConfigType()
	BOOL bSingleSourceNTP,bSecondarySourceNTP, bNoSourceNTP;

begin
	bSingleSourceNTP = FALSE;
	bSecondarySourceNTP = TRUE;
	bNoSourceNTP = FALSE;
    szMessage = "For creation of configuration files, please select the setup\n" +
		"you want for NTP.  Do you want to set up a:\n";
    AskOptions(EXCLUSIVE, szMessage,
	       "&Single Time Source", bSingleSourceNTP,
	       "&Two Time Sources", bSecondarySourceNTP,
		   "&Specify No Time Sources", bNoSourceNTP);
			
    Enable(BACKBUTTON);
    if (bSingleSourceNTP) then
	    szMessage = "Please enter the IP address of the Time Source.\n";
	    AskText(szMessage, svNTPAddress, svNTPAddress);
		CreateConfigFiles(ONETIMESOURCE);   // create ntp.conf
    endif;
	
    if (bSecondarySourceNTP) then
	    szMessage = "Please enter the IP address of the First Time Source from\n" +
		    "which you will RECEIVE synchronization\n";
	    AskText(szMessage, svNTPAddress, svNTPAddress);
		szMessage = "Please enter the IP address of the Second Time Source from\n" +
			"which you will RECEIVE synchronization\n";
		AskText(szMessage, svNTPAddress2, svNTPAddress2);
		CreateConfigFiles(TWOTIMESOURCES);   // create ntp.conf
    endif;
	
	if (bNoSourceNTP) then
		CreateConfigFiles(NOTIMEYET);   // create ntp.conf and ntp.drift
	endif;
	
    if (AskYesNo("Do you want to see the NTP configuration file which has\n" +
		     "been created for this host?\n", YES) = YES) then
		// Let them see/edit the files, if they want to:
		LaunchAppAndWait("NOTEPAD.EXE", WINDIR ^ "ntp.conf",1);
	endif;
end;


///////////////////////////////////////////////////////////////////////////////
//
//  Function: CreateConfigFiles
//
//  Purpose: Now that we know the domain name, host name, and IP Address,
//            create the configuration files for this NTP to be of type
//            specified by parameter:
//                                  ONETIMESOURCE
//                                  TWOTIMESOURCES
//                                  NOTIMEYET
//
//    Need to have filled in:
//                              svNTPAddress
//                              svNTPAddress2
//
//  History:  Greg Schueman	Created		1996/1/1 (yyyy/mm/dd)
//
/////////////////////////////////////////////////////////////////////////
function CreateConfigFiles(nType)
	NUMBER nvFileHandle;
	STRING svInAddrArpa;
	STRING saveddir;
	STRING svIP;

begin

    CreateFile(nvFileHandle,WINDIR,"ntp.conf");
    WriteLine(nvFileHandle,"#");
    WriteLine(nvFileHandle,"#    File:       ntp.conf");
    WriteLine(nvFileHandle,"#    Purpose:    give the NTP Service its startup parameters and");
    WriteLine(nvFileHandle,"#                list of startup files.");
    WriteLine(nvFileHandle,"# ");
    WriteLine(nvFileHandle,"# ");

	WriteLine(nvFileHandle,"#");
	WriteLine(nvFileHandle,"# Miscellaneous stuff");
	WriteLine(nvFileHandle,"#");
	WriteLine(nvFileHandle,"driftfile %windir%\\ntp.drift        # path for drift file");
	WriteLine(nvFileHandle,"# statsdir c:\\var\\ntp\\stats\\     # directory for statistics files");
	WriteLine(nvFileHandle,"# filegen peerstats file peerstats type day enable");
	WriteLine(nvFileHandle,"# filegen loopstats file loopstats type day enable");
	WriteLine(nvFileHandle,"# filegen clockstats file clockstats type day enable");

	if (nType != NOTIMEYET) then
	    WriteLine(nvFileHandle,"#    Need to set up time sources...");
	    WriteLine(nvFileHandle,"#    server ip-address");
        WriteLine(nvFileHandle,"# ");
	    WriteLine(nvFileHandle,"# ");
	endif;
	
	
	if (nType = TWOTIMESOURCES) then
		WriteLine(nvFileHandle,"# ");
		WriteLine(nvFileHandle,"server " + svNTPAddress);
	    WriteLine(nvFileHandle,"server " + svNTPAddress2);
        WriteLine(nvFileHandle,"# ");
  	    WriteLine(nvFileHandle,"# ");
	endif;

	if (nType = ONETIMESOURCE) then
		WriteLine(nvFileHandle," ");
		WriteLine(nvFileHandle,"server " + svNTPAddress);
        WriteLine(nvFileHandle," ");
  	    WriteLine(nvFileHandle," ");
	endif;

    CloseFile(nvFileHandle);
	
	CreateFile(nvFileHandle,WINDIR,"ntp.drift");
    WriteLine(nvFileHandle,"0 0");
	CloseFile(nvFileHandle);

end;


///////////////////////////////////////////////////////////////////////////////
//
//  Function: ReportError
//
//  Purpose: Send intelligible error messages to the user.
//
//  History:  Paul Wren	Created		1995/12/1 (yyyy/mm/dd)
//
///////////////////////////////////////////////////////////////////////////////
function ReportError(n_Err, sz_Message)

begin
  switch(n_Err)
	case k_PrivilegeErr:              sz_Message = "Privilege Error";
	case k_CreateKeyErr:              sz_Message = "Create Key Failed";
	case k_RestoreKeyErr:             sz_Message = "Restore Default Key Failed";
	case k_ErrUnableToOpenWriteOwner: sz_Message = "Unable to Open and Write Owner Information";
	case k_ErrUnableToSetOwner:       sz_Message = "Unable to Set Owner Information";
	case k_ErrUnableToOpenDAC:        sz_Message = "Unable to Open Access Control List";
	case k_ErrUnableToWriteDACL:      sz_Message = "Unable to Write Access Control List";
	case k_OpenKeyError:              sz_Message = "Unable to Open Registry Key Entry";
	case k_ModifySetAccountFail:      sz_Message = "Unable to Setup Account Parameters";
	case k_SCMErr:                    sz_Message = "Unable to Open Service Control Manager Database";
	case k_SCMpoErr:                  sz_Message = "Unable to Open NTP - NT service entries in the Service Control Manager";
	case k_DeleteServiceFail:         sz_Message = "Unable to delete NTP - NT service";
	case k_DeleteKeyFail:             sz_Message = "Unable to delete registry key information";
	case k_DeleteValueFail:           sz_Message = "Unable to delete registry value information";
	case k_DirSecurityErr:            sz_Message = "Unable to retreive Security information on directory";
	case k_DirSetDACLErr:             sz_Message = "Unable to add security information on directory";
	case k_DirSetSecurityErr:         sz_Message = "Unable to set directory security information";
	case k_SCMpoStopErr:              sz_Message = "Unable to stop the NTP - NT service";
	case k_SaveKeyErr:                sz_Message = "Unable to save registry key.";
	case k_ServiceUnknownErr:         sz_Message = "The service control manager could not start the NTP - NT service - please check the event log";
	case k_ServiceDependency:         sz_Message = "The NTP - NT service depends on several other services which are not installed.";
	case k_ServiceDependencyFail:     sz_Message = "The NTP - NT service depends on other services which failed to start.";
	case k_ServiceLogonFail:          sz_Message = "The service manager was unable to login the NTP - NT service - Please check the password and logon as service privilege";
    case k_BadPath:                   sz_Message = "Bad Path Specified.";
	case k_AccessDenied:              sz_Message = "Access Denied.";
	case k_ServiceExists:             sz_Message = "NTP - NT service already exists so cannot be re-installed";
    case k_createservicefailed:       sz_Message = "Creation of the NTP - NT service failed.";
    case k_removeservicefailed:       sz_Message = "Unable to remove the NTP - NT service.";
	case k_ServicenoExists:           sz_Message = "NTP - NT service is not installed so cannot be removed.";
	default:                          sz_Message = "Unknown Error";
  endswitch;
end;




// --- include script file section ---

#include "service.rul"
#include "sddialog.rul"





