1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
// Copyright 2020-2021 Ian Jackson and contributors to Otter
// SPDX-License-Identifier: AGPL-3.0-or-later
// There is NO WARRANTY.

use crate::prelude::*;
use crate::commands::*;

pub struct MgmtChannel<R:Read, W:Write> {
  pub read:  FrameReader<R>,
  pub write: FrameWriter<W>,
}

impl<R,W> Debug for MgmtChannel<R,W> where R: Read, W: Write {
  #[throws(fmt::Error)]
  fn fmt(&self, f: &mut fmt::Formatter) {
    f.write_str("MgmtChannel{...}")?
  }
}

pub type ClientMgmtChannel = MgmtChannel<
    Box<dyn ReadDebug  + Send + 'static>,
    Box<dyn WriteDebug + Send + 'static>,
  >;

pub trait ReadDebug: Read + Debug { }
pub trait WriteDebug: Write + Debug { }
impl<T> ReadDebug for T where T: Read + Debug { }
impl<T> WriteDebug for T where T: Write + Debug { }

impl ClientMgmtChannel {
  #[throws(AE)]
  pub fn connect(socket_path: &str) -> Self {
    let unix = UnixStream::connect(socket_path)
      .with_context(||socket_path.to_owned())
      .context("connect to server")?; 
    let read = unix.try_clone().context("dup the client connection")?;
    let write = unix;
    MgmtChannel::new_boxed(read, write)
  }

  pub fn new_boxed<R,W>(read: R, write: W) -> Self
  where R: ReadDebug  + Send + 'static,
        W: WriteDebug + Send + 'static {
    MgmtChannel::new_raw(Box::new(read), Box::new(write))
  }
}

impl MgmtChannel<TimedFdReader,TimedFdWriter> {
  #[throws(AE)]
  pub fn new_timed<U>(conn: U) -> Self
  where U: IoTryClone + Read + Write + IntoRawFd + Send + 'static,
  {
    let read = conn.try_clone().context("dup the command stream")?;
    let read = TimedFdReader::new(read).context("set up timed reader")?;
    let write = TimedFdWriter::new(conn).context("set up timed writerr")?;
    MgmtChannel::new_raw(read, write)
  }
}

impl<R,W> MgmtChannel<R,W> where R: Read, W: Write + Send {
  pub fn new_raw(read: R, write: W) -> Self  {
    let read = FrameReader::new(read);
    let write = FrameWriter::new(write);
    MgmtChannel { read, write }
  }

  pub fn read_inner_mut(&mut self) -> &mut R {
    self.read.inner_mut()
  }
}

impl ClientMgmtChannel {
  pub const PROGRESS: ProgressUpdateMode = PUM::Duplex;

  #[throws(AE)]
  pub fn cmd_withbulk<U,D>(&mut self, cmd: &MgmtCommand,
                           up: &mut U, down: &mut D,
                           progress: &mut dyn termprogress::Reporter)
                           -> MgmtResponse
  where U: Read + Send, D: Write,
  {
    use MgmtResponse::*;
    let mut wbulk = self.write
      .write_withbulk().context("start sending command")?
      .respond(&cmd).context("send command")?;
    let read = &mut self.read;

    let (resp, mut rbulk) = crossbeam_utils::thread::scope(|scope| {
      let thr = scope.spawn(move |_| {
        io::copy(up, &mut wbulk).context("copy")?;
        wbulk.finish().context("finish")?;
        Ok::<_,AE>(())
      });

      let (mut resp, mut rbulk) =
        read.read_withbulk()
        .context("failed to read response")?;

      while let MR::Progress(pi) = resp {
        resp = (&mut rbulk).read_rmp()?;
        progress.report(&pi);
      }

      let r = thr.join().expect("bulk data upload thread paniced");
      if let Err(e) = r {
        progress.clear();
        warn!("bulk data upload failed: {}", e);
      }
      Ok::<_,AE>((resp, rbulk))
    })
      .expect("bulk data upload thread panicked, not reaped")
      ?;

    progress.clear();
    match &resp {
      Progress(_) => panic!(),
      Fine | AccountsList{..} | GamesList{..} |
      Libraries(_) | LibraryItems(_) | Bundles{..} | Bundle{..} => { },
      SshKeys(..) | SshKeyAdded{..} | ThisConnAuthBy{..} => { },
      AlterGame { error: None, .. } => { },
      Error { error } => {
        Err(error.clone()).context(
          format!("got error response to: {:?}",&cmd)
        )?;
      },
      AlterGame { error: Some(error), ref responses } => {
        if let MgmtCommand::AlterGame { insns, .. } = &cmd {
          if responses.len() < insns.len() {
            Err(error.clone())
              .with_context(|| format!("{:?}", &insns[responses.len()]))
              .context("AlterGame insn failed")?;
          }
        }
        Err(error.clone()).context(format!(
          "game alterations failed (maybe partially); response to: {:?}",
          &cmd
        ))?;
      }
    };

    io::copy(&mut rbulk, down).context("copy bulk download")?;
    resp
  }

  #[throws(AE)]
  pub fn cmd(&mut self, cmd: &MgmtCommand) -> MgmtResponse {
    self.cmd_withbulk(cmd, &mut io::empty(), &mut io::sink(),
                      &mut termprogress::Null)?
  }

  pub fn for_game(self, game: InstanceName, how: MgmtGameUpdateMode)
                  -> MgmtChannelForGame {
    MgmtChannelForGame {
      chan: self,
      game, how
    }
  }
}

pub trait IoTryClone: Sized {
  fn try_clone(&self) -> io::Result<Self>;
}

impl IoTryClone for UnixStream {
  fn try_clone(&self) -> io::Result<UnixStream> { self.try_clone() }
}


#[derive(Debug,Deref,DerefMut)]
pub struct MgmtChannelForGame {
  #[deref] #[deref_mut] pub chan: ClientMgmtChannel,
  pub game: InstanceName,
  pub how: MgmtGameUpdateMode,
}

impl MgmtChannelForGame {
  #[throws(AE)]
  pub fn alter_game(&mut self, insns: Vec<MgmtGameInstruction>,
                f: Option<&mut dyn FnMut(&MgmtGameResponse) -> Result<(),AE>>)
                -> Vec<MgmtGameResponse> {
    let insns_len = insns.len();
    let cmd = MgmtCommand::AlterGame {
      game: self.game.clone(), how: self.how,
      insns
    };
    let responses = match self.cmd(&cmd)? {
      MgmtResponse::AlterGame { error: None, responses }
      if responses.len() == insns_len ||
         responses.iter().any(|r| matches!(r, MGR::InsnExpanded)) => {
        responses
      },
      wat => Err(anyhow!("unexpected AlterGame response: {:?} => {:?}",
                         &cmd, &wat))?,
    };
    if let Some(f) = f {
      for response in &responses {
        f(response)?;
      }
    }
    responses
  }

  #[throws(AE)]
  pub fn info(&mut self) -> MgmtGameResponseGameInfo {
    let resp = self.alter_game(vec![MGI::Info], None)?;
    match &resp[..] {
      [MGR::Info(info)] => info.clone(),
      x => throw!(anyhow!("unexpected response to game Info: {:?}", &x)),
    }
  }

  #[throws(AE)]
  pub fn has_player(&mut self, account: &AccountName)
                    -> Option<(PlayerId, MgmtPlayerInfo)>
  {
    let players = {
      let MgmtGameResponseGameInfo { players, .. } = self.info()?;
      players
    };

    players.into_iter().find(
      |(_,mpi)| &mpi.account == account
    )
  }

  #[throws(AE)]
  pub fn list_pieces(&mut self) -> (Vec<MgmtGamePieceInfo>, BTreeSet<String>) {
    let insns = vec![ MGI::ListPieces ];
    let mut responses = self.alter_game(insns, None)?;
    match responses.as_mut_slice() {
      [MGR::Pieces { pieces, pcaliases }] => return (
        mem::take(pieces),
        mem::take(pcaliases),
      ),
      wat => Err(anyhow!("ListPieces => {:?}", &wat))?,
    }
  }

  #[throws(AE)]
  pub fn list_items(&mut self, lib: Option<String>, pat: String)
                -> Vec<ItemEnquiryData> {
    let cmd = MgmtCommand::LibraryListByGlob {
      game: self.game.clone(),
      lib, pat,
    };
    let mut items = match self.cmd(&cmd)? {
      MgmtResponse::LibraryItems(items) => items,
      wat => Err(anyhow!("unexpected LibraryListByGlob response: {:?}",
                         &wat))?,
    };
    items.sort();
    items
  }

/*
  fn get_info(&mut self) -> Result<
      (MgmtGameResponseGameInfo, HashMap<String,PlayerId>
      ),AE>
  {
    let mut players = self.alter_game(
      vec![ MgmtGameInstruction::Info ],
      None,
    )?;
    let info = match players.pop() {
      Some(MgmtGameResponse::Info(info)) => info,
      wat => Err(anyhow!("GetGstate got {:?}", &wat))?,
    };
    let mut nick2id = HashMap::new();
    for (player, pstate) in info.players.iter() {
      use hash_map::Entry::*;
      match nick2id.entry(pstate.nick.clone()) {
        Occupied(oe) => Err(anyhow!("game has duplicate nick {:?}, {} {}",
                                    &pstate.nick, *oe.get(), player))?,
        Vacant(ve) => ve.insert(player),
      };
    }
    Ok((info, nick2id))
  }
*/
}