#!/bin/sh
#
# shell script to create Bacula SQLite tables
#
# Copyright (C) 2000-2017 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#

bindir=@SQLITE_BINDIR@
PATH="$bindir:$PATH"
cd @working_dir@
db_name=@db_name@

sqlite3 $* ${db_name}.db <<END-OF-DATA
CREATE TABLE Filename (
  FilenameId INTEGER,
  Name TEXT DEFAULT '',
  PRIMARY KEY(FilenameId) 
  );

CREATE INDEX inx1 ON Filename (Name);

CREATE TABLE Path (
   PathId INTEGER,
   Path TEXT DEFAULT '',
   PRIMARY KEY(PathId) 
   );

CREATE INDEX inx2 ON Path (Path);

-- In File table
-- FileIndex can be 0 for FT_DELETED files
-- FileNameId can link to Filename.Name='' for directories
CREATE TABLE File (
   FileId INTEGER,
   FileIndex INTEGER UNSIGNED NOT NULL,
   JobId INTEGER UNSIGNED REFERENCES Job NOT NULL,
   PathId INTEGER UNSIGNED REFERENCES Path NOT NULL,
   FilenameId INTEGER UNSIGNED REFERENCES Filename NOT NULL,
   DeltaSeq SMALLINT UNSIGNED DEFAULT 0,
   MarkId INTEGER UNSIGNED DEFAULT 0,
   LStat VARCHAR(255) NOT NULL,
   MD5 VARCHAR(255) NOT NULL,
   PRIMARY KEY(FileId) 
   );
CREATE INDEX inx3 ON File (JobId);
CREATE INDEX file_jpf_idx ON File (JobId, PathId, FilenameId);
--
-- Possibly add one or more of the following indexes
--  if your Verifies are too slow.
--
-- CREATE INDEX inx4 ON File (PathId);
-- CREATE INDEX inx5 ON File (FileNameId);


CREATE TABLE RestoreObject (
   RestoreObjectId INTEGER,
   ObjectName TEXT DEFAULT '',
   RestoreObject TEXT DEFAULT '',
   PluginName TEXT DEFAULT '',
   ObjectLength INTEGER DEFAULT 0,
   ObjectFullLength INTEGER DEFAULT 0,
   ObjectIndex INTEGER DEFAULT 0,
   ObjectType INTEGER DEFAULT 0,
   FileIndex INTEGER UNSIGNED DEFAULT 0,
   ObjectCompression INTEGER DEFAULT 0,
   JobId INTEGER UNSIGNED REFERENCES Job NOT NULL,
   PRIMARY KEY(RestoreObjectId)
   );
CREATE INDEX restore_jobid_idx ON RestoreObject (JobId);


CREATE TABLE Job (
   JobId INTEGER,
   Job VARCHAR(128) NOT NULL,
   Name VARCHAR(128) NOT NULL,
   Type CHAR(1) NOT NULL,
   Level CHAR(1) NOT NULL,
   ClientId INTEGER REFERENCES Client DEFAULT 0,
   JobStatus CHAR(1) NOT NULL,
   SchedTime DATETIME NOT NULL,
   StartTime DATETIME DEFAULT 0,
   EndTime DATETIME DEFAULT 0,
   RealEndTime DATETIME DEFAULT 0,
   JobTDate BIGINT UNSIGNED DEFAULT 0,
   VolSessionId INTEGER UNSIGNED DEFAULT 0,
   VolSessionTime INTEGER UNSIGNED DEFAULT 0,
   JobFiles INTEGER UNSIGNED DEFAULT 0,
   JobBytes BIGINT UNSIGNED DEFAULT 0,
   ReadBytes BIGINT UNSIGNED DEFAULT 0,
   JobErrors INTEGER UNSIGNED DEFAULT 0,
   JobMissingFiles INTEGER UNSIGNED DEFAULT 0,
   PoolId INTEGER UNSIGNED REFERENCES Pool DEFAULT 0,
   FileSetId INTEGER UNSIGNED REFERENCES FileSet DEFAULT 0,
   PriorJobId INTEGER UNSIGNED REFERENCES Job DEFAULT 0,
   PurgedFiles TINYINT DEFAULT 0,
   HasBase TINYINT DEFAULT 0,
   HasCache TINYINT DEFAULT 0,
   Reviewed TINYINT DEFAULT 0,
   Comment TEXT,
   FileTable TEXT DEFAULT 'File',
   PRIMARY KEY(JobId) 
   );
CREATE INDEX inx6 ON Job (Name);
CREATE INDEX job_jobtdate_inx ON Job (JobTDate);

-- Create a table like Job for long term statistics 
CREATE TABLE JobHisto (
   JobId INTEGER,
   Job VARCHAR(128) NOT NULL,
   Name VARCHAR(128) NOT NULL,
   Type CHAR(1) NOT NULL,
   Level CHAR(1) NOT NULL,
   ClientId INTEGER DEFAULT 0,
   JobStatus CHAR(1) NOT NULL,
   SchedTime DATETIME NOT NULL,
   StartTime DATETIME DEFAULT 0,
   EndTime DATETIME DEFAULT 0,
   RealEndTime DATETIME DEFAULT 0,
   JobTDate BIGINT UNSIGNED DEFAULT 0,
   VolSessionId INTEGER UNSIGNED DEFAULT 0,
   VolSessionTime INTEGER UNSIGNED DEFAULT 0,
   JobFiles INTEGER UNSIGNED DEFAULT 0,
   JobBytes BIGINT UNSIGNED DEFAULT 0,
   ReadBytes BIGINT UNSIGNED DEFAULT 0,
   JobErrors INTEGER UNSIGNED DEFAULT 0,
   JobMissingFiles INTEGER UNSIGNED DEFAULT 0,
   PoolId INTEGER UNSIGNED DEFAULT 0,
   FileSetId INTEGER UNSIGNED DEFAULT 0,
   PriorJobId INTEGER UNSIGNED DEFAULT 0,
   PurgedFiles TINYINT DEFAULT 0,
   HasBase TINYINT DEFAULT 0,
   HasCache TINYINT DEFAULT 0,
   Reviewed TINYINT DEFAULT 0,
   Comment TEXT,
   FileTable TEXT DEFAULT 'File'
   );
CREATE INDEX inx61 ON JobHisto (StartTime);

CREATE TABLE Location (
   LocationId INTEGER,
   Location TEXT NOT NULL,
   Cost INTEGER DEFAULT 0,
   Enabled TINYINT,
   PRIMARY KEY(LocationId)
   );

CREATE TABLE LocationLog (
   LocLogId INTEGER,
   Date DATETIME NOT NULL,
   Comment TEXT NOT NULL,
   MediaId INTEGER UNSIGNED REFERENCES Media DEFAULT 0,
   LocationId INTEGER UNSIGNED REFERENCES LocationId DEFAULT 0,
   NewVolStatus VARCHAR(20) NOT NULL,
   NewEnabled TINYINT NOT NULL,
   PRIMARY KEY(LocLogId)
);


CREATE TABLE Log (
   LogId INTEGER,
   JobId INTEGER UNSIGNED REFERENCES Job NOT NULL,
   Time DATETIME NOT NULL,
   LogText TEXT NOT NULL,
   PRIMARY KEY(LogId) 
   );
CREATE INDEX LogInx1 ON Log (JobId);


CREATE TABLE FileSet (
   FileSetId INTEGER,
   FileSet VARCHAR(128) NOT NULL,
   MD5 VARCHAR(25) NOT NULL,
   CreateTime DATETIME DEFAULT 0,
   PRIMARY KEY(FileSetId)
   );

CREATE INDEX fileset_name_idx on FileSet (FileSet);

CREATE TABLE JobMedia (
   JobMediaId INTEGER,
   JobId INTEGER UNSIGNED REFERENCES Job NOT NULL,
   MediaId INTEGER UNSIGNED REFERENCES Media NOT NULL,
   FirstIndex INTEGER UNSIGNED NOT NULL,
   LastIndex INTEGER UNSIGNED NOT NULL,
   StartFile INTEGER UNSIGNED DEFAULT 0,
   EndFile INTEGER UNSIGNED DEFAULT 0,
   StartBlock INTEGER UNSIGNED DEFAULT 0,
   EndBlock INTEGER UNSIGNED DEFAULT 0,
   VolIndex INTEGER UNSIGNED DEFAULT 0,
   PRIMARY KEY(JobMediaId) 
   );

CREATE INDEX inx7 ON JobMedia (JobId, MediaId);


CREATE TABLE Media (
   MediaId INTEGER,
   VolumeName VARCHAR(128) NOT NULL,
   Slot INTEGER DEFAULT 0,
   PoolId INTEGER UNSIGNED REFERENCES Pool DEFAULT 0,
   MediaType VARCHAR(128) NOT NULL,
   MediaTypeId INTEGER UNSIGNED REFERENCES MediaType DEFAULT 0,
   LabelType TINYINT DEFAULT 0,
   FirstWritten DATETIME DEFAULT 0,
   LastWritten DATETIME DEFAULT 0,
   LabelDate DATETIME DEFAULT 0,
   VolJobs INTEGER UNSIGNED DEFAULT 0,
   VolFiles INTEGER UNSIGNED DEFAULT 0,
   VolBlocks INTEGER UNSIGNED DEFAULT 0,
   LastPartBytes BIGINT UNSIGNED DEFAULT 0,
   VolMounts INTEGER UNSIGNED DEFAULT 0,
   VolBytes BIGINT UNSIGNED DEFAULT 0,
   VolABytes BIGINT UNSIGNED DEFAULT 0,
   VolAPadding BIGINT UNSIGNED DEFAULT 0,
   VolHoleBytes BIGINT UNSIGNED DEFAULT 0,
   VolHoles INTEGER UNSIGNED DEFAULT 0,
   VolType INTEGER UNSIGNED DEFAULT 0,
   VolParts INTEGER UNSIGNED DEFAULT 0,
   VolCloudParts INTEGER UNSIGNED DEFAULT 0,
   VolErrors INTEGER UNSIGNED DEFAULT 0,
   VolWrites BIGINT UNSIGNED DEFAULT 0,
   VolCapacityBytes BIGINT UNSIGNED DEFAULT 0,
   VolStatus VARCHAR(20) NOT NULL,
   Enabled TINYINT DEFAULT 1,
   Recycle TINYINT DEFAULT 0,
   ActionOnPurge     TINYINT	DEFAULT 0,
   CacheRetention BIGINT UNSIGNED DEFAULT 0,
   VolRetention BIGINT UNSIGNED DEFAULT 0,
   VolUseDuration BIGINT UNSIGNED DEFAULT 0,
   MaxVolJobs INTEGER UNSIGNED DEFAULT 0,
   MaxVolFiles INTEGER UNSIGNED DEFAULT 0,
   MaxVolBytes BIGINT UNSIGNED DEFAULT 0,
   InChanger TINYINT DEFAULT 0,
   StorageId INTEGER UNSIGNED REFERENCES Storage DEFAULT 0,
   DeviceId INTEGER UNSIGNED REFERENCES Device DEFAULT 0,
   MediaAddressing TINYINT DEFAULT 0,
   VolReadTime BIGINT UNSIGNED DEFAULT 0,
   VolWriteTime BIGINT UNSIGNED DEFAULT 0,
   EndFile INTEGER UNSIGNED DEFAULT 0,
   EndBlock INTEGER UNSIGNED DEFAULT 0,
   LocationId INTEGER UNSIGNED REFERENCES Location DEFAULT 0,
   RecycleCount INTEGER UNSIGNED DEFAULT 0,
   InitialWrite DATETIME DEFAULT 0,
   ScratchPoolId INTEGER UNSIGNED REFERENCES Pool DEFAULT 0,
   RecyclePoolId INTEGER UNSIGNED REFERENCES Pool DEFAULT 0,
   Comment TEXT,
   PRIMARY KEY(MediaId)
   );

CREATE UNIQUE INDEX Media_Volumename_Id ON Media (VolumeName);
CREATE INDEX inx8 ON Media (PoolId);
CREATE INDEX inx9 ON Media (StorageId);


CREATE TABLE MediaType (
   MediaTypeId INTEGER,
   MediaType VARCHAR(128) NOT NULL,
   ReadOnly TINYINT DEFAULT 0,
   PRIMARY KEY(MediaTypeId)
   );

CREATE TABLE Storage (
   StorageId INTEGER,
   Name VARCHAR(128) NOT NULL,
   AutoChanger TINYINT DEFAULT 0,
   PRIMARY KEY(StorageId)
   );

CREATE TABLE Device (
   DeviceId INTEGER,
   Name VARCHAR(128) NOT NULL,
   MediaTypeId INTEGER UNSIGNED REFERENCES MediaType NOT NULL,
   StorageId INTEGER UNSIGNED REFERENCES Storage,
   DevMounts INTEGER UNSIGNED DEFAULT 0,
   DevReadBytes BIGINT UNSIGNED DEFAULT 0,
   DevWriteBytes BIGINT UNSIGNED DEFAULT 0,
   DevReadBytesSinceCleaning BIGINT UNSIGNED DEFAULT 0,
   DevWriteBytesSinceCleaning BIGINT UNSIGNED DEFAULT 0,
   DevReadTime BIGINT UNSIGNED DEFAULT 0,
   DevWriteTime BIGINT UNSIGNED DEFAULT 0,
   DevReadTimeSinceCleaning BIGINT UNSIGNED DEFAULT 0,
   DevWriteTimeSinceCleaning BIGINT UNSIGNED DEFAULT 0,
   CleaningDate DATETIME DEFAULT 0,
   CleaningPeriod BIGINT UNSIGNED DEFAULT 0,
   PRIMARY KEY(DeviceId)
   );


CREATE TABLE Pool (
   PoolId INTEGER,
   Name VARCHAR(128) NOT NULL,
   NumVols INTEGER UNSIGNED DEFAULT 0,
   MaxVols INTEGER UNSIGNED DEFAULT 0,
   UseOnce TINYINT DEFAULT 0,
   UseCatalog TINYINT DEFAULT 1,
   AcceptAnyVolume TINYINT DEFAULT 0,
   CacheRetention BIGINT UNSIGNED DEFAULT 0,
   VolRetention BIGINT UNSIGNED DEFAULT 0,
   VolUseDuration BIGINT UNSIGNED DEFAULT 0,
   MaxVolJobs INTEGER UNSIGNED DEFAULT 0,
   MaxVolFiles INTEGER UNSIGNED DEFAULT 0,
   MaxVolBytes BIGINT UNSIGNED DEFAULT 0,
   AutoPrune TINYINT DEFAULT 0,
   Recycle TINYINT DEFAULT 0,
   ActionOnPurge     TINYINT	DEFAULT 0,
   PoolType VARCHAR(20) NOT NULL,
   LabelType TINYINT DEFAULT 0,
   LabelFormat VARCHAR(128) NOT NULL,
   Enabled TINYINT DEFAULT 1,
   ScratchPoolId INTEGER UNSIGNED REFERENCES Pool DEFAULT 0,
   RecyclePoolId INTEGER UNSIGNED REFERENCES Pool DEFAULT 0,
   NextPoolId INTEGER UNSIGNED REFERENCES Pool DEFAULT 0,
   MigrationHighBytes BIGINT UNSIGNED DEFAULT 0,
   MigrationLowBytes BIGINT UNSIGNED DEFAULT 0,
   MigrationTime BIGINT UNSIGNED DEFAULT 0,
   UNIQUE (Name),
   PRIMARY KEY (PoolId)
   );

CREATE INDEX pool_name_idx on Pool (Name);

CREATE TABLE Client (
   ClientId INTEGER,
   Name VARCHAR(128) NOT NULL,
   Uname VARCHAR(255) NOT NULL,   -- uname -a field
   AutoPrune TINYINT DEFAULT 0,
   FileRetention BIGINT UNSIGNED DEFAULT 0,
   JobRetention  BIGINT UNSIGNED DEFAULT 0,
   UNIQUE (Name),
   PRIMARY KEY(ClientId)
   );

CREATE UNIQUE INDEX client_name_idx on Client (Name);

CREATE TABLE BaseFiles (
   BaseId BIGINT,
   BaseJobId INTEGER UNSIGNED REFERENCES Job NOT NULL,
   JobId INTEGER UNSIGNED REFERENCES Job NOT NULL,
   FileId INTEGER UNSIGNED REFERENCES File NOT NULL,
   FileIndex INTEGER UNSIGNED,
   PRIMARY KEY(BaseId)
   );

CREATE INDEX basefiles_jobid_idx ON BaseFiles ( JobId );

CREATE TABLE UnsavedFiles (
   UnsavedId INTEGER,
   JobId INTEGER UNSIGNED REFERENCES Job NOT NULL,
   PathId INTEGER UNSIGNED REFERENCES Path NOT NULL,
   FilenameId INTEGER UNSIGNED REFERENCES Filename NOT NULL,
   PRIMARY KEY (UnsavedId)
   );


CREATE TABLE Version (
   VersionId INTEGER UNSIGNED NOT NULL 
   );


CREATE TABLE Counters (
   Counter TEXT NOT NULL,     
   MinValue INTEGER DEFAULT 0, 
   MaxValue INTEGER DEFAULT 0,
   CurrentValue INTEGER DEFAULT 0,
   WrapCounter TEXT NOT NULL,
   PRIMARY KEY (Counter)
   );

CREATE TABLE CDImages (
   MediaId INTEGER UNSIGNED NOT NULL,
   LastBurn DATETIME NOT NULL,
   PRIMARY KEY (MediaId)
   );

CREATE TABLE PathHierarchy
(
     PathId integer NOT NULL,
     PPathId integer NOT NULL,
     CONSTRAINT pathhierarchy_pkey PRIMARY KEY (PathId)
);

CREATE INDEX pathhierarchy_ppathid 
	  ON PathHierarchy (PPathId);

CREATE TABLE PathVisibility
(
      PathId integer NOT NULL,
      JobId integer NOT NULL,
      Size int8 DEFAULT 0,
      Files int4 DEFAULT 0,
      CONSTRAINT pathvisibility_pkey PRIMARY KEY (JobId, PathId)
);

CREATE INDEX pathvisibility_jobid
	  ON PathVisibility (JobId);


CREATE TABLE Snapshot (
  SnapshotId	  serial,
  Name		  text NOT NULL,
  JobId 	  integer default 0,
  FileSetId	  integer default 0,
  CreateTDate	  bigint default 0,
  CreateDate	  datetime not null,
  ClientId	  int default 0,
  Volume	  text not null,
  Device	  text not null,
  Type		  text not null,
  Retention	  int default 0,
  Comment	  text,
  primary key (SnapshotId)
);

CREATE UNIQUE INDEX snapshot_idx ON Snapshot (Device, Volume, Name);

CREATE TABLE Status (
   JobStatus CHAR(1) NOT NULL,
   JobStatusLong BLOB, 
   Severity INT,
   PRIMARY KEY (JobStatus)
   );

INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('C', 'Created, not yet running',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('R', 'Running',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('B', 'Blocked',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('T', 'Completed successfully', 10);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('E', 'Terminated with errors', 25);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('e', 'Non-fatal error',20);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('f', 'Fatal error',100);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('D', 'Verify found differences',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('A', 'Canceled by user',90);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('F', 'Waiting for Client',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('S', 'Waiting for Storage daemon',15);
INSERT INTO Status (JobStatus,JobStatusLong) VALUES
   ('m', 'Waiting for new media');
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('M', 'Waiting for media mount',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('s', 'Waiting for storage resource',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('j', 'Waiting for job resource',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('c', 'Waiting for client resource',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('d', 'Waiting on maximum jobs',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('t', 'Waiting on start time',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('p', 'Waiting on higher priority jobs',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('a', 'SD despooling attributes',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('i', 'Doing batch insert file records',15);
INSERT INTO Status (JobStatus,JobStatusLong,Severity) VALUES
   ('I', 'Incomplete Job',25);

-- Initialize Version		 
INSERT INTO Version (VersionId) VALUES (16);

PRAGMA default_cache_size = 100000;
PRAGMA synchronous = NORMAL;

END-OF-DATA

echo ""
echo "WARNING: !!!! SQLite3 is no longer supported. !!!!"
echo "WARNING: !!!! Please switch to MySQL or PostgreSQL !!!!"
echo "WARNING: !!!!  as soon as possible. !!!!"
echo ""

chmod 640 ${db_name}.db
exit 0
