-- Copyright (c) 2007-2010 Ben Bucksch
-- BSD 3-clause license

-- DROP DATABASE zeipis; -- deletes old database
CREATE DATABASE zeipis;
USE DATABASE zeipis;

-- system setup

CREATE TABLE device (
  deviceid          smallint unsigned NOT NULL auto_increment, -- myid
  devicetype        varchar(10) NOT NULL, -- "DVB", "Analog" XXX needed?
  devicesubtype     varchar(10) default NULL, -- "DVB-S", "DVB-S2", "DVB-T", "DVB-C", "ATSC", "Analog SW", "Analog HW" XXX numeric?
  host              varchar(255) NOT NULL, -- where the card is plugged in or the recorder process runs
  dvb_num           tinyint(4) unsigned default NULL, -- N in /dev/dvb/adapterN/dvr0
  dvb_fullts        boolean default FALSE, -- if false, let hardware or driver filter the PIDs. Otherwise we'll do that, needed for recording > 1 channels from the same card/transponder at the same time
  dvb_encrypt_systems   varchar(100) default NULL, -- Which CA systems the CAM(s) and smartcard(s) in this card support(s). see channel.dvb_encrypt_systems
  analog_videodev   varchar(100) default NULL, --
  analog_analogdev  varchar(100) default NULL, --
  PRIMARY KEY (deviceid)
);

CREATE TABLE store (
  storename       varchar(255) NOT NULL, -- myid
  host            varchar(255) NOT NULL, -- on which computer the store is localed
  directoryname   varchar(1000) NOT NULL, -- directory on the host where the store root is
  PRIMARY KEY (storename)
);

CREATE TABLE prefs (
  prefkey        varchar(30) NOT NULL, -- dot-separated key defined by the application
  value_int      bigint(20) default NULL,
  value_boolean  boolean default NULL,
  value_str      varchar(1000) default NULL,
  PRIMARY KEY (prefkey)
);

-- channel

CREATE TABLE station ( -- the program. If the same content is distributed via e.g. DVB-T and DVB-C and analog PAL, it's 1 station with 3 channels.
  stationid         int unsigned NOT NULL auto_increment,
  long_name         varchar(255) NOT NULL, -- User-visible name, long version
  short_name        varchar(10) NOT NULL, -- User-visible name, short version
  xmltvid           varchar(255) default NULL, -- the XMLTV ID per grabber, e.g. 4.bbc.co.uk for BBC4
  icon              varchar(1000) default NULL, -- filename of png
  preset            smallint default NULL, -- The number that the user can enter with the remote. Also used for sorting. If NULL, it gets added at the end.
  station_group     varchar(30) default NULL, -- allows user or grabber or group channels, e.g. by a pay-tv company or "Local"
  commercial_free   boolean default FALSE, -- no advertizing. Up to defintion.
  auto              boolean default FALSE, -- @see channel.auto
  disabled          boolean default FALSE, -- Hide this station. Useful for channels/stations found by channel scan, but user doesn't want them, e.g. home shopping, 900-call-in and similar crap channels.
  PRIMARY KEY (stationid)
);
CREATE TABLE channel ( -- the technical reception
  channelid           int unsigned NOT NULL auto_increment,
  stationid           int unsigned NOT NULL,
  tech_name           varchar(255) default NULL, -- name on air in datastream, e.g. "ProSieben". Not shown to user in normal use. For DVB: DVB service name. For analog: VBI name.
  dvb_provider_name   varchar(30) default NULL,
  channeltype         varchar(10) NOT NULL, -- same as device.devicetype currently
  dvb_transponderid   smallint unsigned default NULL,
  dvb_serviceid       mediumint unsigned default NULL, -- for metadata from DVB stream
  -- dvb_pid_vid      smallint unsigned default NULL, -- video stream
  -- dvb_pid_aud      smallint unsigned default NULL, -- main audio soundtrack: main language, and usually MPEG2Layer2 stereo
  -- dvb_pid_aud_org  smallint unsigned default NULL, -- original language soundtrack
  -- dvb_pid_aud_ac3  smallint unsigned default NULL, -- AC3 soundtrack
  languages           varchar(50) default "", -- languages in which the audio track of this station is broadcasted. comma-separated list of ISO-639-1 2-letter language codes, no spaces, e.g. "en,de,es". TODO in station?
  dvb_encrypted       boolean default FALSE, -- the channel is scrambled and can only be decoded with a fitting CAM and smartcard
  dvb_encrypt_systems varchar(100) default NULL, -- Which CAM systems are able to decrypt the channel. Comma-separated list of integers (decimal, not hex, no spaces).
  analog_frequency    varchar(5) default NULL, -- e.g. "E10". XXX
  quality             smallint default 0 NOT NULL, -- how good the signal is, where are less commercials etc.. hint for scheduler.
  auto                boolean default FALSE, -- has been added by channel scan. Keep to FALSE when adding channels manually. They then won't be touched (updated, deleted) by the channel scan.
  disabled            boolean default FALSE, -- don't use this channel
  PRIMARY KEY (channelid),
  KEY stationid (stationid),
  KEY dvb_transportid (dvb_transponderid)
);
CREATE TABLE dvb_transponder ( -- for tuning (on DVB, several channels are in a bundle called multiplex, which is on a transponder = the physical reception)
  dvb_transponderid   int unsigned NOT NULL auto_increment,
  dvbsubtype          varchar(10) NOT NULL, -- "DVB-S", "DVB-S2", "DVB-T", "DVB-C", "ATSC"
  frequency           int unsigned NOT NULL, -- in KHz for DVB-S*, e.g. 12480000. In Hz for the rest? XXX
  symbolrate          int unsigned NOT NULL, -- in sym/s, e.g. 27500000
  polarity             char(1) NOT NULL, -- v = vertical, h = horizontal (later: l = left, r = right)
  -- frontend types: QAM (DVB-C), OFDM (DVB-T), QPSK (DVB-S). The following are the specific settings within these types.
  modulation          varchar(10) default 'auto', -- QAM_AUTO, QAM_16, QAM_32, QAM_64, QAM_128, QAM_256 (DVB-C, DVB-T, ATSC only 64 and 256), 8VSB, 16VSB (ATSC), PSK8, APSK16, APSK32 (?), QPSK (DVB-S (always), DVB-S2, DVB-T), DQPSK. DVB-T is OFDM, but using modulation field for constellation here.
  fec_inner           varchar(10) default 'auto', -- DVB-C, DVB-S: 1/2, 2/3, 3/4, 4/5, 5/6, 6/7, 7/8, 8/9, 9/10, 3/5, auto, none
  inversion           char(1) default 'a', -- DVB-T, DVB-C: 0 = on, 1 = off, a = auto
  bandwidth           char(1) default 'a', -- DVB-T: 6, 7 or 8 MHz or auto
  hp_code_rate        varchar(10) default 'auto', -- DVB-T: same as fec_inner. "high priority" for poor reception.
  lp_code_rate        varchar(10) default 'auto', -- DVB-T: same as fec_inner. "low priority" for good reception.
  transmission_mode   char(1) default 'a', -- DVB-T: 2K, 8K, auto
  guard_interval      varchar(10) default 'auto', -- DVB-T: 1/4, 1/8, 1/16, 1/32, auto
  hierarchy           varchar(10) default 'auto', -- DVB-T: 1, 2, 4, none, auto
  rolloff             varchar(10) default 'auto', -- DVB-S2: 20, 25, 35, auto
  pilot               varchar(1) default 'a', -- DVB-S2: 1 = on, 1 = off, a = auto
  transportid         int default NULL,
  networkid           int default NULL,
  -- serviceversion      smallint(6) default 0,
  updatetimestamp     timestamp(14) NOT NULL,
  PRIMARY KEY (dvb_transponderid)
);
CREATE TABLE pidcache (
  channelid           int NOT NULL default 0,
  pid                 smallint NOT NULL default -1,
  tableid             int(11) NOT NULL default -1,
  KEY channelid (channelid)
);
CREATE TABLE device_channel ( -- which cards can record the channel?
  deviceid            int unsigned NOT NULL,
  channelid           int unsigned NOT NULL,
  UNIQUE KEY mapping (deviceid, channelid),
  KEY deviceid (deviceid),
  KEY channelid (channelid)
);


-- TV schedule data from grabber

CREATE TABLE broadcast ( -- airing at a certain time on a certain station
  broadcastid       bigint(20) unsigned NOT NULL auto_increment,
  filmid            bigint(20) unsigned NOT NULL,
  stationid         int unsigned NOT NULL,
  starttime         datetime NOT NULL,
  endtime           datetime NOT NULL,
  PRIMARY KEY (broadcastid),
  UNIQUE KEY start (stationid, starttime),
  KEY starttime (starttime),
  KEY endtime (endtime)
);
CREATE TABLE film ( -- Some unique bit of content, e.g. movie, series episode, certain news broadcast etc.. ("show" is reserved in SQL)
  filmid              bigint(20) unsigned NOT NULL auto_increment,
  title               varchar(255) NOT NULL,
  subtitle            varchar(255) NOT NULL default '', -- Name of episode. Empty (or punchline) for movies.
  original_title      varchar(255) default NULL, -- title, but in original language
  original_subtitle   varchar(255) default NULL, -- subtitle, but in original language
  description         text default NULL,
  showtype            varchar(10) default NULL, -- "movie", "series", "sports", "tvshow", "news"
  genre               varchar(127) default NULL, -- e.g. "Actionthriller"
  seriesid            varchar(127) default NULL, -- Identifies this series. E.g. "1234567" for 'Star Trek: TNG. From grabber.
  episodeid           varchar(127) default NULL, -- Identifies this episode. E.g. "2/4" for the 2. episode of the 4. season of 'Star Trek: TNG'. From grabber, ideally from producer. XXX Human-readable?
  firstshown          smallint(4) default NULL, -- When was this first published, ever. E.g. 1990
  quality_rating      float default NULL, -- How good is this show? 0 = crap, 1 = best (e.g. 5 of 5 stars), NULL = not rated. XXX Several systems? Ratings by our user?
  sourceid            varchar(50) NOT NULL, -- Unique ID for show (e.g. 'Star Trek' episode 'Metamorphosis' or a news broadcast on a certain day) from upstream grabber source; only used during import, for identification of repetitions / re-runs.
  xmltv               text default NULL, -- full source of XML from grabber. XXX good idea?
  PRIMARY KEY (filmid),
  UNIQUE KEY sourceid (sourceid),
  KEY title (title)
);
CREATE TABLE person (
  personid            int(16) unsigned NOT NULL auto_increment,
  realname            varchar(255) NOT NULL, -- name of actor/director
  PRIMARY KEY (personid),
  KEY realname (realname)
);
CREATE TABLE credits (
  filmid              bigint(20) unsigned NOT NULL,
  function            varchar(20) NOT NULL, -- "actor", "director", ...
  personid            int(16) unsigned NOT NULL, -- actor etc.
  role                varchar(127) default NULL, -- name of figure in movie
  KEY filmid (filmid),
  KEY personid (personid)
);


-- recordings

CREATE TABLE recording ( -- both planned and done recordings
  recordid          int(10) unsigned NOT NULL auto_increment,
  filmid            bigint(20) unsigned NOT NULL,
  done              tinyint(1) default FALSE, -- FALSE = planned, TRUE = has been fully recorded, 2 = recording in progress, 3 = redo?
  seen              boolean default FALSE, -- user has watched most of this show. Can help with the autodeletion.
  deleted           boolean default FALSE, -- this has been recorded in the past, but user deleted the file. can be used to prevent re-recodings of seen shows from a year ago which just get repeated by the station now.
  host              varchar(255) default NULL, -- the hostname of the Store where the file can be found TODO needed?
  storename         varchar(255) default NULL, -- the Store where the file can be found
  filename          varchar(1000) default NULL, -- filename on the Store host. relative path not including store directory
  rec_group         varchar(127) default 'Standard', -- allows the user to sort recordings in groups
  error_log         text default NULL, -- if the recording went wrong, this is the human-readable log to tell the user why and clues on how to fix/prevent it.
  error_msg         varchar(255) default NULL, -- dito, but a "title" for the error, a concise and pointed description of the main root problem
  keep              boolean default FALSE, -- never auto delete
  -- TODO length
  bookmark          varchar(128) default NULL, -- XXX
  PRIMARY KEY (recordid),
  KEY filmid (filmid)
);
CREATE TABLE recording_plan ( -- additional fields for planned recordings
  recordid          int(10) unsigned NOT NULL,
  priority          smallint(4) signed default 0, -- which recording to prefer, if 2 recordings conflict. higher wins. up to scheduler what this means in detail.
  searchtype        smallint(2) unsigned NOT NULL, -- 1 = exactly this airing, once, 2 = this film once (allow reschedule), 3 = always, no dups, 4 = like 3, but on this channel only, 5 = once every day at this time on this station, 6 = once every week on this station, 7 = custom search, always, no dups, 8 = always, dup detection based on subtitle and description instead of ID, 9 = always, no dup detection, 10 = custom search 
  custom_search     varchar(2000) default NULL, -- if searchtype = 7
  -- allow_lower_quality
  -- allow_later
  -- allow_other_station
  -- allow_preempt_higher_priority
  -- rec_starttime     datetime NOT NULL, -- the time/channel to record on. first filled out by planner, changed by scheduler
  rec_stationid     smallint(6) unsigned NOT NULL default 0, -- dito
  -- rec_device        smallint(5) unsigned default NULL, -- dito. filled out by scheduler (not planner). XXX needed?
  PRIMARY KEY (recordid)
);


-- permissions

GRANT ALL ON zeipis.* TO zeipis@localhost IDENTIFIED BY "zei-pis";
-- GRANT ALL ON zeipis.* TO zeipis@'192.168.1.%' IDENTIFIED BY "zei-pis";
-- GRANT ALL ON zeipis.* TO zeipis@'%' IDENTIFIED BY "zei-pis";
FLUSH PRIVILEGES;
